Academy / Advanced Level: HTML and CSS
CSS Architecture and Methodologies
CSS-in-JS: Styled Components and Emotion
CSS-in-JS is a modern approach to writing CSS directly in JavaScript. Popular libraries like Styled Components and Emotion allow developers to write modular, scoped CSS inside React components. This ensures that styles are tightly coupled with the components they apply to.
Example with Styled Components:
import styled from 'styled-components';
const Button = styled.button`
background-color: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
&:hover {
background-color: #2980b9;
}
`;
export default function App() {
return <Button>Click Me</Button>;
}
In this example:
- The
Buttoncomponent has its styles written in Styled Components, ensuring that styles are scoped to that component alone. - CSS-in-JS improves modularity, reusability, and maintainability in component-driven applications like React.
Key Benefits of CSS-in-JS:
- Scoped Styles: Styles are scoped to the component, avoiding global CSS conflicts.
- Dynamic Styles: You can use JavaScript to define dynamic styles based on component props or state.
- Maintainability: Since styles are colocated with the component, it's easier to maintain and update them.