HTML & CSS Course
HTML & CSS
/
Advanced

CSS Modules

Definition

A CSS file in which all class names and animation names are scoped locally by default.

Explain Like I'm New

The ultimate solution to CSS conflicts in React/Next.js. If you write `.button { color: red; }` in a CSS Module, the compiler automatically renames your class to something insane like `.Button_button__3xyz`. Because the name is random, it is impossible for it to conflict with another button on your site.

Real World Example

Used natively in Next.js. You create a file named `Button.module.css`, and import it directly into your React component. You get the power of vanilla CSS with the safety of scoped styles.

Common Use Cases

  • •React/Next.js applications
  • •Preventing global CSS bleed

Interactive Example

/* 
  Note: This is a conceptual example of how CSS Modules work in React.
  It requires a build step to function.
*/

/* File: Card.module.css */
/*
.container {
  background: white;
  border-radius: 8px;
}
.title {
  color: blue;
}
*/

/* File: Card.jsx */
/*
import styles from './Card.module.css';

export default function Card() {
  // The bundler turns 'styles.container' into an ugly, unique string!
  return (
    <div className={styles.container}>
      <h2 className={styles.title}>Hello World</h2>
    </div>
  );
}
*/

/* HTML Output in the Browser: */
<div class="Card_container__2x8z9">
  <h2 class="Card_title__9a2b1">Hello World</h2>
</div>

Interview Questions

basic

  • What problem do CSS Modules solve perfectly?

intermediate

  • Do you write regular CSS syntax inside a CSS Module file?

Flash Cards

Question

What problem?

Click to reveal answer
Answer

Global Scope. In standard CSS, every class is global. If two developers create a `.card` class in different files, the browser merges them, breaking the design. CSS Modules scope the class to the exact file it was imported into.

Question

Syntax?

Click to reveal answer
Answer

Yes! Unlike Styled Components or Tailwind, a CSS Module is literally just a standard `.css` file. The magic happens during the JavaScript build step (Webpack/Vite).