CSS Modules
CSS Modules are a popular way to style Next.js applications. They let you write CSS that's scoped to specific components, preventing style conflicts and making your code more maintainable.
Think of CSS Modules like personal containers for each component. Each component gets its own isolated CSS that doesn't leak out or conflict with other styles.
Creating CSS Modules
To create a CSS Module, you name your CSS file with the .module.css extension. Next.js automatically treats these files as CSS Modules.
/* components/Button.module.css */
.button {
background-color: #0070f3;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: #0051a8;
}
The CSS classes are automatically scoped to the component that imports them.
Using CSS Modules
Import the CSS Module in your component and use the class names as properties:
import styles from './Button.module.css';
export default function Button({ children, onClick }) {
return (
<button
className={styles.button}
onClick={onClick}
>
{children}
</button>
);
}
The styles object contains all the CSS class names from your module. This approach prevents naming conflicts because each component gets its own scoped classes.
Dynamic Styling
CSS Modules work great with dynamic styles. You can conditionally apply classes based on props or state:
import styles from './Card.module.css';
export default function Card({ variant, children }) {
const classNames = [
styles.card,
variant === 'primary' ? styles.primary : styles.secondary,
].join(' ');
return (
<div className={classNames}>
{children}
</div>
);
}
This pattern makes it easy to create flexible, reusable components with different visual variants.
Benefits of CSS Modules
CSS Modules offer several advantages for Next.js development:
Scope isolation: Styles are automatically scoped to components, preventing global conflicts.
Familiar syntax: You write standard CSS, so there's no learning curve.
Type safety: IDEs can autocomplete class names and catch errors.
Performance: Only the CSS needed for a component is loaded, reducing bundle size.
CSS Modules are a great choice for projects that want scoped styling without additional complexity.