Sub topic 2
What CSS Modules give you
This chapter explains what CSS Modules are, which problems they solve, and what they do not solve. You will see the idea in a small example. Later chapters cover file setup, applying classes, composition and tooling in detail.
It assumes you know basic React (components, props, JSX), CSS selectors, the cascade and specificity, ES module imports, and roughly what a bundler such as Vite, webpack or Next.js does.
The problem CSS Modules address
Plain CSS has one global namespace. Every .button rule in every stylesheet applies to every element with that class, no matter which component rendered it. This causes several problems as an app grows:
- Name collisions. Two teams write
.titlefor different components. Whichever stylesheet loads last wins, and both components change. - Load-order dependence. When two rules have equal specificity, source order decides. Source order depends on import order and code splitting, so a style can break when you move an import.
- Defensive naming. To avoid collisions, people invent long prefixes such as
.checkout-summary__title--large. This works only as long as everyone follows the convention. - Fear of deleting. You cannot tell whether
.titleis used elsewhere, so unused rules stay in the codebase.
React components are small, self-contained units. Global CSS works against that, because a component's appearance depends on rules defined somewhere else.
The core idea
CSS Modules is a build-time transform. A CSS file whose name ends in .module.css is treated as a module. Its class names are local to that file by default. The bundler rewrites each class name into a unique one, and it gives your JavaScript an object that maps the original names to the rewritten ones.
CSS Modules is not a library you add to React, and it adds no runtime code for scoping. It is a convention that bundlers understand. The syntax is ordinary CSS plus two additions, composes and :global.
Here is the idea in miniature. You write this:
.title {
font-size: 1.25rem;
font-weight: 600;
}import styles from './Card.module.css';
export function Card({ title }) {
return <h2 className={styles.title}>{title}</h2>;
}The browser receives something like this:
.Card_title__x7Fq2 {
font-size: 1.25rem;
font-weight: 600;
}<h2 class="Card_title__x7Fq2">Welcome</h2>The exact format of the generated name depends on your tool and configuration. Some tools include the file name and a hash, and others produce only a short hash. Treat the name as opaque.
The build pipeline
The transform happens when you build or run the dev server. At that point the bundler does two jobs from one source file.
The two outputs stay consistent because they come from the same transform. If the CSS file renames a class, the JavaScript object changes with it.
What you gain
Local scope by default
A class in a .module.css file cannot collide with a class of the same name in another module. Two components can each define .title or .button and neither affects the other. You no longer need prefixes or naming schemes such as BEM to prevent collisions.
Explicit dependencies
A component imports the styles it uses, so the dependency is visible in the code, like any other import. You can open a component and find its styles from its import list. Deleting a component and its module file removes its styles with it.
Plain CSS with no runtime cost
Your styles remain real CSS files. You can use pseudo-classes, media queries, container queries, custom properties, @keyframes and nesting if your toolchain supports it. The browser receives a normal stylesheet, which it can cache and parse separately from JavaScript. CSS-in-JS libraries that compute styles at runtime add JavaScript work. CSS Modules does not.
A familiar mental model
If you know CSS, you already know most of CSS Modules. You do not learn a new styling API, and designers or engineers who read CSS can review the files.
Tooling support
Vite, Next.js, Create React App and webpack with css-loader all support .module.css files. Most need little or no configuration. Chapter on tooling covers the details.
What you do not get
CSS Modules changes how class names are scoped. It does not change the rest of CSS, so these limits matter.
- Only class and ID selectors are scoped. Element selectors such as
h2 { ... }and attribute selectors stay global. A module file containing a bareh2rule styles everyh2on the page. Pure-mode tooling can reject such selectors, and some tools enable it by default. - Inheritance and the cascade still apply. An element still inherits
colorandfont-familyfrom its ancestors. Global styles, such as a CSS reset, still affect module-styled elements. - Specificity still applies. A scoped
.titlecan lose to a more specific global rule. Scoping removes accidental name matches but does not make rules override each other any differently. - Generated names are not a stable API. Names can change between builds or configurations. Do not write tests or external CSS that depend on them.
- Dynamic styling needs another mechanism. Class names are fixed at build time, so a value that is only known at runtime, such as a progress percentage, needs inline styles or CSS custom properties. A later chapter covers this.
CSS Modules compared with nearby approaches
| Approach | Scope | Runtime cost | Styles live in |
|---|---|---|---|
| Global CSS | None, one namespace | None | `.css` files |
| BEM or other naming conventions | By discipline only | None | `.css` files |
| CSS Modules | Per file, enforced at build time | None for scoping | `.module.css` files |
| CSS-in-JS (runtime) | Per component | Styles computed in the browser | JavaScript or TypeScript files |
| Utility classes (such as Tailwind) | Not scoped, but classes are small and shared | None | Markup |
The main difference from naming conventions is enforcement. BEM relies on people following the rules, and CSS Modules makes a collision impossible for local classes. The main difference from runtime CSS-in-JS is that your CSS stays in CSS files and the browser does the work.
When CSS Modules is a good fit
Choose CSS Modules when:
- Components own their styles and few rules are shared across components.
- You want plain CSS, a small learning curve and no runtime overhead.
- Your framework already supports
.module.cssfiles, as Next.js and Vite do.
Look at other options when you need styles computed heavily from props at runtime, or when your team already uses a utility-class system and wants a single approach.
A first look at the scoping rule
To see the effect, imagine two components that each define .title:
/* Card.module.css */
.title {
color: #111827;
}/* Alert.module.css */
.title {
color: #b91c1c;
}After the transform, the two rules target different generated names, such as Card_title__x7Fq2 and Alert_title__k9Lm4. A card title stays dark gray and an alert title stays red, regardless of which file loads first. With global CSS, both components would get whichever rule came last.
Key points
- CSS Modules is a build-time transform for files named
*.module.css. - Class names in such files are local by default and are rewritten to unique names.
- Your code imports an object that maps the names you wrote to the generated names.
- Only class and ID selectors are scoped. Element selectors, inheritance and specificity behave as in ordinary CSS.
- There is no runtime library, so the cost is the build step.
Exercise
A teammate adds h2 { margin: 0; } to Card.module.css and is surprised that an h2 in a different component also loses its margin. Why does this happen, and how should they fix it?
Show answer
CSS Modules scopes only class and ID selectors. The bare h2 element selector stays global, so it matches every h2 on the page. The fix is to give the card's heading a class, for example .heading { margin: 0; }, and apply it with className={styles.heading}.
Exercise
Two modules, Card.module.css and Alert.module.css, both define .title. Why do they not conflict, and what would you see in the rendered HTML?
Show answer
The bundler rewrites each local class name into a unique generated name, for example Card_title__x7Fq2 and Alert_title__k9Lm4. The rendered elements carry those different class names, so each rule matches only its own component. The exact name format depends on the tool and configuration.