Sub topic 5
How class names become locally scoped
This chapter explains what happens to a class name between your .module.css file and the browser. It assumes you can import a CSS Module and apply a class with styles.something. It also assumes you know CSS specificity and have used a bundler such as Vite, webpack, or Next.js.
The scoping happens at build time
CSS itself has no local scope. Every class selector matches any element in the document. CSS Modules gets around this by rewriting names before the code ships. No library runs in the browser.
During the build, the bundler's CSS pipeline does three things:
- It parses each
.module.cssfile and finds the class names, ids, and animation names. - It replaces each local name with a generated name that is unique to that file.
- It emits two outputs: the rewritten CSS, and a JavaScript object that maps your original names to the generated ones.
The object from step 3 is the default export you get from import styles from './Button.module.css'. By the time the page loads, the browser sees only ordinary global class names. They are unique, so they do not collide.
A concrete before and after
Two components each define a .title class.
/* Card.module.css */
.title {
font-size: 1.25rem;
color: #111827;
}/* Modal.module.css */
.title {
font-size: 2rem;
color: #b91c1c;
}In plain global CSS, the second .title would override or merge with the first. With CSS Modules, the build output looks roughly like this. The hashes are illustrative, and yours will differ.
.Card_title__3kQ9z {
font-size: 1.25rem;
color: #111827;
}
.Modal_title__7xPd2 {
font-size: 2rem;
color: #b91c1c;
}The JavaScript side receives one object per file.
import cardStyles from './Card.module.css';
import modalStyles from './Modal.module.css';
console.log(cardStyles);
// { title: 'Card_title__3kQ9z' }
console.log(modalStyles);
// { title: 'Modal_title__7xPd2' }
console.log(cardStyles.title === modalStyles.title); // falseThe source name title is the key. The generated name is the value. When you write className={cardStyles.title}, you are looking up a string in this object.
What goes into a generated name
A generated name is built from a template. The default in many setups combines the file name, the local class name, and a short hash:
| Part | Example | Purpose |
|---|---|---|
| File name | `Card` | Makes the name readable in dev tools |
| Local name | `title` | Shows which class it came from |
| Hash | `3kQ9z` | Guarantees uniqueness across files |
The hash is derived from the file's path and the local name. Two consequences follow:
- The output is deterministic. Building the same project twice gives the same names, which keeps long-lived caches valid.
- Moving or renaming a file can change its hashes. Do not store generated names anywhere outside the build.
Many production setups use shorter templates, such as a hash only, to reduce file size. A name like _a1b2c tells you nothing about its origin, which is another reason not to depend on the format.
Changing the format
You can change the template. In Vite, set css.modules.generateScopedName:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
css: {
modules: {
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
});In webpack's css-loader, the equivalent option is modules.localIdentName. Framework wrappers such as Next.js choose a template for you and expose little or no control over it.
What counts as local
Scoping applies to names that you define and that the stylesheet is free to rename. In a CSS Module, these are local by default:
- Class selectors, such as
.title. - Id selectors, such as
#header. @keyframesnames, and references to them inanimationandanimation-name.
Everything else is left alone. That includes element selectors (a, h1), attribute selectors ([type="text"]), pseudo-classes (:hover), and custom properties (--progress).
The keyframes case surprises people, so here it is in full:
/* Spinner.module.css */
.spinner {
width: 24px;
height: 24px;
border: 3px solid #e5e7eb;
border-top-color: #2563eb;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}The build renames spin to something like Spinner_spin__9fLw1, and it rewrites the animation declaration to match. Another file that also defines @keyframes spin gets its own unique name, so the two cannot clash.
Every class in a selector is rewritten
Scoping works per name, not per rule. In a compound or descendant selector, each class is rewritten on its own.
.card .title:hover {
text-decoration: underline;
}This becomes:
.Card_card__aa11b .Card_title__cc22d:hover {
text-decoration: underline;
}Both classes come from the same file, so the rule still works as written. The descendant relationship in the DOM is unchanged.
Scoping does not change specificity
Rewriting a name does not add weight to the selector. A selector with one class has the same specificity before and after the build. The cascade also still applies: if two rules have equal specificity, the one that comes later in the final CSS wins.
This matters in two situations:
- Mixed global and module styles. A global stylesheet such as
.btn { color: red; }has the same specificity as.Button_button__x1y2z { color: blue; }. Whichever loads later wins. Do not assume the module rule is protected. - Two modules that style the same element. If you pass a class from one module to a component that applies its own module class, the order in which the bundler emits the two files decides the result.
The leak: unscoped element selectors
Because element selectors are not renamed, this rule is global even though it lives in a module:
/* Article.module.css */
h2 {
margin-top: 2rem;
}The compiled CSS still contains h2 { margin-top: 2rem; }, and it applies to every h2 on the page once the file is loaded. The usual fix is to anchor the element selector to a local class:
.article h2 {
margin-top: 2rem;
}Now the selector requires an ancestor with the generated .article class, so it only matches inside that component. Some build tools reject a selector with no local class in module mode. This is called pure mode, and webpack's css-loader offers it as an option (mode: 'pure'). If your setup has it, turn it on.
Reading the mapping yourself
The mapping is a plain object, so you can inspect it. This is useful when a style does not apply and you want to know why.
import styles from './Button.module.css';
export function Debug() {
return <pre>{JSON.stringify(styles, null, 2)}</pre>;
}Three results are common:
- The key exists and the value looks right. The lookup works, so check the CSS rules and specificity.
- The key is missing. You misspelled the class, or the class only appears in a selector that the pipeline did not export as a standalone class.
- The whole object is empty or
undefined. The file was not treated as a module. The usual cause is a file name that lacks the.module.csssuffix.
Looking up a missing key returns undefined. React omits the class attribute when className is undefined, so the element renders unstyled and no error appears.
Do not depend on generated names
The generated names are an implementation detail of the build. Treat them as opaque strings.
- Do not write selectors against them in tests, such as
document.querySelector('.Card_title__3kQ9z'). The name changes when the file moves or the hash template changes. - Do not copy them into other stylesheets.
- Do not use them as stable hooks for analytics or end-to-end tests. Use
data-testidor an accessible role instead.
Exercise
Two files, A.module.css and B.module.css, both define .item. A component imports both as a and b. What does a.item === b.item evaluate to, and why? What happens to a rule li { margin: 0 } in A.module.css?
Show answer
It evaluates to false. The build gives each file's .item a different generated name (the file name and path feed into the hash), so the two lookups return different strings. The rule li { margin: 0 } is not rewritten, because element selectors are not scoped. It stays global and applies to every li on the page. To limit it, write something like .list li { margin: 0 } so it requires a local class.
Exercise
A teammate writes an end-to-end test with document.querySelector('.Card_title__3kQ9z'). It passes locally and fails after the CI build uses a shorter hash template. What went wrong, and what is a better hook?
Show answer
The test depends on a generated name, which comes from the build configuration and the file path. The CI build used a different template, so the name changed. A better hook is a data-testid attribute on the element, or a query by accessible role or text, since neither depends on how class names are generated.