Blog>
Snippets

Applying CSS Modules in Next.js for Component-Level Styling

Demonstrate how to create and use CSS modules to apply styles scoped to individual components, avoiding style leakage.
// Button.module.css
.button {
  background-color: #0070f3;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.button:hover {
  background-color: #0056d2;
}
This is a CSS module file named Button.module.css. Define your component-specific styles here. The '.button' class will be scoped to the component that imports this CSS module, preventing style leakage.
import styles from './Button.module.css';

export default function Button({ children }) {
  return (
    <button className={styles.button}>
      {children}
    </button>
  );
}
This is a JavaScript file for a Button component. It imports the CSS module using the 'import' statement and applies the imported styles to the 'button' element using 'className={styles.button}'. The styles are applied to this specific component only.
// SomeOtherComponent.module.css
.anotherClass {
  /* Some other component-specific styles */
}
If you have another component that needs its own scoped styles, create another CSS module file like SomeOtherComponent.module.css for it.
import React from 'react';
import anotherStyles from './SomeOtherComponent.module.css';

const SomeOtherComponent = () => {
  return (
    <div className={anotherStyles.anotherClass}>
      {/* Component content */}
    </div>
  );
};

export default SomeOtherComponent;
In this JavaScript file, we import and use another CSS module for 'SomeOtherComponent'. The classes are accessed via the imported 'anotherStyles' object. Each class is scoped to this component only.