CSS Modules: Local Scope for Your Styles
CSS Modules treat your styles like local variables. Instead of a global stylesheet, each CSS file is scoped to the component that imports it, preventing name collisions in component-based apps.
WHY IT EXISTS Classic CSS has one global scope. Any style can override any other, leading to specificity wars, !important abuse, and fragile codebases that are hard to maintain. As applications grew into component-based architectures, a way to lock styles to their components became necessary to prevent chaos.
THE MENTAL MODEL Think of CSS Modules as giving your CSS files their own private namespace. Just as a variable defined inside a function isn't accessible globally, a class named .title in Button.module.css won't conflict with a class of the same name in Header.module.css. Your styles become predictable and encapsulated.
HOW IT WORKS During your build process, a tool like Webpack or Vite processes your CSS file. For every class you write (e.g., .className), it generates a unique, globally safe class name (e.g., _Component_className_a8f4c). It then creates a JavaScript object that maps your original names to the new unique names. When you import the CSS file in your JavaScript, you get this mapping object. You use this object to apply the correct, unique class to your HTML elements.
WHEN TO USE IT Use CSS Modules when building applications with a component-based architecture (React, Vue, Svelte, etc.). It's ideal for creating self-contained, reusable UI components where you want to guarantee styles won't leak in or out. This makes your styling system predictable and easier to refactor.
WHEN NOT TO USE IT Avoid CSS Modules for simple, static websites with minimal JavaScript, where a single global stylesheet is easier to manage. They also add a layer of abstraction that's overkill if you're not using a JS framework or a build step. For truly global styles like typography, CSS resets, or design tokens, traditional global CSS is often still the right tool.
ONE CANONICAL EXAMPLE You write a simple CSS file, Button.css: .error { color: red; }. In your JavaScript component, you import it: import styles from './Button.css';. To apply the style, your JSX or template would look like <button className={styles.error}>Delete</button>. The final HTML rendered in the browser will be something like <button class="_Button_error_1a2b3c">Delete</button>, with a corresponding unique CSS rule in the stylesheet.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.