Sub topic 3
Creating and importing a .module.css file
This chapter covers the mechanics of a CSS Modules file: how to name it, where to put it, how to import it, and what the import gives you at runtime. It assumes you know basic React (components, props, JSX), CSS selectors and specificity, and ES module imports. It also assumes you have a bundler such as Vite, webpack or Next.js running a React project. How generated class names are built, and the other ways to use the styles object, come in later chapters.
The file naming convention
A CSS Module is an ordinary CSS file with one change: its name ends in .module.css. The bundler checks the file name and applies local scoping only to files that match. A file named Button.css is processed as plain global CSS, even if you import it the same way.
Other preprocessor extensions follow the same pattern, such as .module.scss and .module.less. These need the matching preprocessor installed.
By convention the CSS Module sits next to the component it styles and shares its base name:
src/
components/
Button/
Button.jsx
Button.module.cssThis layout keeps a component's markup and styles together. Deleting the component folder removes its styles too, so nothing is left behind in a shared stylesheet.
Writing the stylesheet
The contents are normal CSS. You write class selectors the way you always have, and nothing in the syntax is special.
.button {
padding: 0.5rem 1rem;
border: 0;
border-radius: 4px;
background: #2563eb;
color: #fff;
cursor: pointer;
}
.button:hover {
background: #1d4ed8;
}The name .button is a local name. In a global stylesheet, any element on the page with class="button" would match this rule. In a CSS Module, the bundler rewrites .button to a unique name at build time, so only code that imports this file can reach it. Two different components can each define .button without colliding.
Importing the file
You import the file from the component with a default import and name the result, usually styles:
import styles from './Button.module.css';
export function Button({ children }) {
return <button className={styles.button}>{children}</button>;
}The default export is a plain JavaScript object. Each key is a class name from your CSS file, and each value is the unique class name the bundler generated for it. For the stylesheet above, the object looks roughly like this:
{ button: "Button_button__x7Qa2" }The exact string depends on your bundler and its configuration, so treat it as opaque. When styles.button is evaluated, React receives that generated string and renders it as the class attribute. The browser then matches it against the rewritten selector in the emitted CSS.
The bundler does two jobs for one import:
- It adds the rewritten CSS to the page, either in a
<link>tag or injected<style>tags, depending on your setup. - It gives your JavaScript the object that maps your local names to the generated names.
Why the import name does not matter
styles is only a variable name. You can call it anything, and this is useful when a component imports more than one module:
import buttonStyles from './Button.module.css';
import layoutStyles from '../shared/Layout.module.css';
export function Toolbar({ children }) {
return (
<div className={layoutStyles.row}>
<button className={buttonStyles.button}>{children}</button>
</div>
);
}Each import is a separate object with its own scope. A .row defined in another module cannot clash with a .row in yours, because each gets a different generated name.
Using styles for the single-module case is a widespread convention, so most readers will recognize it immediately. Use a descriptive name only when you import several modules.
What happens when a class does not exist
The styles object is a regular object, so a missing key evaluates to undefined. A typo in a class name produces no error:
// The CSS defines .button, but the code reads styles.buton
<button className={styles.buton}>Save</button>React omits the class attribute when className is undefined, so the element renders unstyled and nothing is logged. The same silent failure happens when you rename a class in the CSS file and forget to update the component.
A related trap is building the class string by hand:
<button className={`${styles.button} ${styles.buton}`}>Save</button>Here the second value is undefined, and template literals turn it into the text "undefined". The element gets the class "Button_button__x7Qa2 undefined". The page still works, but the markup is wrong. A later chapter shows a helper that avoids this problem. For now, remember that a missing class fails quietly.
You can catch these typos before they ship. TypeScript can check keys if your CSS Module types are generated per file. A later chapter on TypeScript covers this, and the blanket declaration shown there does not do it.
Importing for side effects only
You can also import a CSS Module without binding a name:
import './Button.module.css';This still adds the CSS to the page, with the class names rewritten. But you have no way to reach the generated names, so none of the rules can ever match an element. It does nothing useful. If you want global styles, use a plain .css file instead. If you want scoped styles, bind the default export.
Scope is per file, not per component
CSS Modules scope names to the file, not to the component that imports it. Two things follow from this.
First, any component can import any module. Nothing stops Card.jsx from importing Button.module.css, and it would get the same generated names as Button.jsx. This is how you intentionally share styles, but it also means you should keep each module owned by one component unless you mean otherwise.
Second, the scoping applies to class names (and a few other identifiers, such as animation names), not to every selector. A bare element selector stays global:
/* Button.module.css */
button {
margin: 0;
}This rule applies to every <button> on the page once the file is loaded, because button is a tag name and not a class. Keep selectors in a module class-based. If you need to style elements inside a component, give them classes.
.card h2 {
margin-top: 0;
}This one is safer. The descendant h2 is only matched inside elements that carry the rewritten .card class. Still, prefer giving the heading its own class if you want to avoid depending on markup structure.
Quick reference for the import
| Item | Detail |
|---|---|
| File name | Must end in `.module.css` (or `.module.scss` and so on) |
| Location | Conventionally next to the component, same base name |
| Import form | `import styles from './Name.module.css'` |
| Value of the import | Object mapping local class names to generated names |
| Missing key | Evaluates to `undefined`, with no error |
| Side-effect import | Loads the CSS but gives you no access to the names |
| Scope boundary | The file, not the component |
Checking that it works
After you add the file and import, run your dev server and inspect the rendered button in the browser's developer tools. You should see three things:
- The element has a class that looks like your local name with a prefix or hash added.
- The Styles panel shows your rules attached to that generated class.
- The original name
buttondoes not appear as a plain class on the element.
If the element has no class, check the import path and the key name. If it has the plain class button with no styling at all, check that the file name really ends in .module.css.
You can also log the object once while developing:
import styles from './Button.module.css';
console.log(styles);The output shows every class the bundler found in the file and the generated name for each. This is a quick way to confirm whether a key exists. Remove the log before committing.
Exercise
You create Card.css containing .title { font-size: 1.5rem; } and import it with import styles from './Card.css'. The page shows no scoping, and styles.title is undefined. What are the two problems, and how do you fix them?
Show answer
The file name does not end in .module.css, so the bundler treats it as global CSS and does not produce a mapping object. In that case there is nothing to import as styles, and .title is also an ordinary global class. Rename the file to Card.module.css and update the import path to ./Card.module.css. The default import then gives an object with a title key, and className={styles.title} applies the scoped rule.
Exercise
In Panel.module.css you write p { color: gray; }. A teammate later reports that paragraphs in unrelated components turned gray. Why did this happen, and what change keeps the style inside the panel?
Show answer
Class names are rewritten, but a bare element selector such as p is not, so the rule applies to every paragraph on the page once the file loads. Give the paragraph a class, for example .note { color: gray; }, and use className={styles.note} on it. You could also scope it with a class ancestor such as .panel p.