Advertisement
Beginner Next.js, Styling in Next.js (CSS Modules, Tailwind & Styled Components)

What are CSS Modules, and how do you use them in a Next.js project?

Short answer

CSS Modules let you write regular CSS in a file named with a .module.css extension, and Next.js automatically scopes those class names so they only apply to the component that imports them, preventing styles from accidentally leaking into or being overridden by other components…

Save Next.js mock interview
Advertisement
AModel answer
CSS Modules let you write regular CSS in a file named with a .module.css extension, and Next.js automatically scopes those class names so they only apply to the component that imports them, preventing styles from accidentally leaking into or being overridden by other components on the page.
/* Button.module.css */
.button {
  background-color: blue;
  color: white;
}

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

export default function Button() {
  return <button className={styles.button}>Click me</button>;
}
Real-world example
A component library uses CSS Modules for each of its button and card components, ensuring their styles never accidentally clash with styles defined elsewhere in a larger application.
Likely follow-ups
  • How does class name scoping actually work behind the scenes with CSS Modules?
  • Can you share common styles between multiple CSS Modules?
Related topics