What CSS Modules Are
You'll learn: How CSS Modules create locally-scoped styles by automatically generating unique class names at build time.
The Problem with Regular CSS
When you write CSS normally in a React app, every class name is global. If you define .button in one component's stylesheet and .button in another, they clash. You end up with naming conventions like BEM (.ComponentName__element--modifier) just to avoid conflicts.
How CSS Modules Solve This
CSS Modules are regular CSS files with a twist: the build tool (Webpack, Vite, etc.) transforms every class name into a unique identifier. You write normal-looking CSS, but at runtime, .button becomes something like .Button_button__a3x8z.
Think of it like JavaScript modules: just as import gives you isolated scopes for variables, CSS Modules give you isolated scopes for class names.
The Developer Experience
You write a file named Button.module.css:
.button {
background: blue;
}
In your component, you import it as an object:
import styles from './Button.module.css';
<button className={styles.button}>Click</button>
The styles object maps your original names to the generated unique ones. Your code reads cleanly (styles.button), but the browser sees the scoped version.
Build-Time Magic
This transformation happens during bundling—not at runtime. The tool rewrites both your CSS and your JavaScript imports to use matching unique identifiers. No runtime overhead, no extra libraries in the bundle.
Key Takeaway: CSS Modules give you component-scoped styles without naming collisions by generating unique class names at build time, letting you write normal CSS with automatic isolation.