CSS Modules
CSS Modules are a popular way to style React components, providing a unique class name for each CSS class. This approach helps to avoid global namespace pollution and makes it easier to manage CSS in large applications. With React 19, CSS Modules have become even more powerful, allowing for more efficient and scalable styling.
Basic Example
To get started with CSS Modules, you need to create a CSS file with a .module.css extension. For example, let’s create a styles.module.css file:
.container {
background-color: #f0f0f0;
padding: 20px;
}Then, in your React component, you can import and use the CSS class like this:
import React from 'react';
import styles from './styles.module.css';
function MyComponent() {
return <div className={styles.container}>Hello World!</div>;
}In this example, the styles.container class is used to style the div element. Note that the className attribute is used to apply the CSS class, rather than the class attribute.
Advanced Usage
CSS Modules also support more advanced features, such as nested selectors and media queries. For example, you can use nested selectors to style child elements:
/* styles.module.css */
.container {
background-color: #f0f0f0;
padding: 20px;
}
.container .header {
font-size: 24px;
font-weight: bold;
}Then, in your React component:
import React from 'react';
import styles from './styles.module.css';
function MyComponent() {
return (
<div className={styles.container}>
<div className={styles.header}>Header</div>
<div>Content</div>
</div>
);
}You can also use media queries to apply different styles based on screen size:
/* styles.module.css */
.container {
background-color: #f0f0f0;
padding: 20px;
}
@media (max-width: 768px) {
.container {
padding: 10px;
}
}Best Practices
Here are some best practices to keep in mind when using CSS Modules:
- Use a consistent naming convention for your CSS classes, such as using camelCase or kebab-case.
- Avoid using global CSS classes, and instead use CSS Modules to scope your styles to specific components.
- Use nested selectors to style child elements, rather than using separate CSS classes.
- Use media queries to apply different styles based on screen size or other conditions.
Key Takeaways
- CSS Modules provide a unique class name for each CSS class, avoiding global namespace pollution.
- Use the
.module.cssextension for your CSS files, and import them in your React components usingimport styles from './styles.module.css';. - Use CSS Modules to scope your styles to specific components, and avoid using global CSS classes.
- Use nested selectors and media queries to style child elements and apply different styles based on screen size or other conditions.