0
0
NextJSframework~5 mins

CSS Modules in NextJS

Choose your learning style9 modes available
Introduction

CSS Modules help keep styles organized and avoid conflicts by making CSS local to components.

When you want to style a React component without affecting other parts of the app.
When multiple developers work on the same project and need to avoid style clashes.
When you want to write CSS that is scoped automatically to a component.
When you want to use CSS with Next.js in a simple and modular way.
Syntax
NextJS
import styles from './Component.module.css';

function Component() {
  return <div className={styles.className}>Hello</div>;
}

CSS files must be named with .module.css to use CSS Modules in Next.js.

Imported styles are objects where keys are class names and values are unique generated class names.

Examples
This example shows a button styled with a CSS Module. The button class is local to this component.
NextJS
/* Button.module.css */
.button {
  background-color: blue;
  color: white;
  padding: 1rem;
}

// Button.jsx
import styles from './Button.module.css';

export default function Button() {
  return <button className={styles.button}>Click me</button>;
}
This example shows a header with a local title style that won't affect other headers.
NextJS
/* Header.module.css */
.title {
  font-size: 2rem;
  color: green;
}

// Header.jsx
import styles from './Header.module.css';

export default function Header() {
  return <h1 className={styles.title}>Welcome</h1>;
}
Sample Program

This component shows a box with a border and padding. The styles come from a CSS Module, so they only apply here.

NextJS
/* styles.module.css */
.container {
  border: 2px solid black;
  padding: 1rem;
  max-width: 300px;
  margin: 1rem auto;
  text-align: center;
}

/* Component.jsx */
import styles from './styles.module.css';

export default function Box() {
  return (
    <div className={styles.container}>
      <p>This box is styled with CSS Modules.</p>
    </div>
  );
}
OutputSuccess
Important Notes

CSS Modules generate unique class names to avoid style conflicts.

You can combine CSS Modules with global styles if needed.

Use descriptive class names to keep your styles clear and maintainable.

Summary

CSS Modules scope CSS to components automatically.

They prevent style conflicts in large projects.

Next.js supports CSS Modules by naming files .module.css.