CSS Modules let you scope styles to a single component by automatically generating unique class names, so you can write plain CSS without worrying about global collisions. You use them by importing a stylesheet into your JavaScript or TypeScript file and then referencing its class names as properties of the imported object. This guide explains how they work, how to set them up, and how they compare to other styling approaches.
What Problem Do CSS Modules Solve?
In traditional CSS, every selector is global. If you write .button in one stylesheet, it affects every element with that class anywhere on the page. In a large project with many components, this leads to naming conflicts, accidental overrides, and the need for complex naming conventions like BEM (Block, Element, Modifier). CSS Modules solve this by making class names local to the file they are defined in. When you import a CSS file as a module, the build tool transforms each class name into a unique, hashed identifier—for example, .button becomes .button_3x7k9. That transformed name is what gets applied to the element, so styles from one component can never leak into another.
How CSS Modules Work Under the Hood
CSS Modules are not a browser feature; they are a build-time transformation. Tools like webpack, Vite, or Parcel process your CSS file and generate two things: a modified stylesheet with unique class names, and a JavaScript object that maps the original class names to the new hashed ones. When you write import styles from './Button.module.css', the styles object contains properties like styles.button that evaluate to the hashed class name. The build tool also injects the transformed CSS into the page, either as a separate file or via JavaScript. This means CSS Modules work with any framework that uses a bundler—React, Vue, Svelte, Angular, and even plain JavaScript.
Setting Up CSS Modules in a Project
Most modern frameworks have CSS Modules support built in. Here is how to enable it in common setups:
- Create React App: No configuration needed. Name your file
Button.module.cssand import it. - Vite: Works out of the box. Use
*.module.cssfiles. - Next.js: Supports CSS Modules by default for files named
*.module.css. - Webpack (manual): Add the
css-loaderwithmodules: trueoption.
If you are using a custom webpack setup, the key configuration looks like this:
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: { modules: true }
}
]
}
Once configured, you can import the module and use it in your component:
import styles from './Button.module.css';
function Button() {
return <button className={styles.button}>Click me</button>
}
Composing and Reusing Styles
CSS Modules support composes, a feature that lets you reuse styles from another class within the same file or from a different file. This is similar to Sass’s @extend but scoped to modules. For example:
/* base.module.css */
.base {
padding: 10px;
border-radius: 4px;
}
/* button.module.css */
.button {
composes: base from './base.module.css';
background-color: blue;
}
When you use styles.button, the element gets both the base and button hashed classes. This promotes reuse without duplicating CSS. Note that composes only works with class selectors, not with tag or ID selectors, and it cannot be used inside media queries or pseudo-classes.
Common Pitfalls and How to Avoid Them
Even though CSS Modules are straightforward, developers often run into a few issues:
- Global elements: To style a global element like
bodyorhtml, you cannot use a class module. Instead, use a regular global CSS file or use the:globalselector::global(body) { margin: 0; }. - Dynamic class names: You cannot construct the class name as a string (e.g.,
styles['btn-' + variant]) because the hashed names are not predictable. Instead, use a lookup object:const classes = { primary: styles.primary, secondary: styles.secondary }. - Multiple classes: To apply multiple classes, use template literals or an array join:
className={`${styles.button} ${styles.active}`}. - Nested selectors: CSS Modules do not support nesting by default. You can use plain CSS or add a preprocessor like Sass, but the class names still get hashed.
CSS Modules vs. Other Styling Approaches
CSS Modules sit between global CSS and CSS-in-JS. Here is a quick comparison:
- Global CSS: Simple, but prone to collisions and specificity wars. No scoping.
- BEM: A naming convention that reduces collisions but relies on discipline. CSS Modules automate this.
- CSS-in-JS (styled-components, Emotion): Scopes styles via JavaScript, allows dynamic theming, but adds runtime overhead and a learning curve.
- Utility-first (Tailwind): Uses predefined classes; no scoping needed because classes are atomic. CSS Modules complement Tailwind by letting you extract repeated patterns.
CSS Modules offer a good balance: they keep CSS in .css files, work with preprocessors, and have zero runtime cost because the transformation happens at build time.
Performance and Bundle Size
CSS Modules have no runtime cost—the browser receives plain CSS with hashed class names. The main trade-off is that each unique class name generates a new selector, which can slightly increase file size compared to hand-optimized CSS. However, the difference is usually negligible. The build tool also deduplicates common styles if you use composes wisely. For code splitting, CSS Modules work well with lazy-loaded components: the CSS is loaded only when the component is imported, which can improve initial load time.
Frequently Asked Questions
Can I use CSS Modules with plain HTML?
No, CSS Modules require a build step and JavaScript to map class names. For plain HTML, you would need to manually apply the hashed class names, which defeats the purpose. Use them in a framework or with a bundler.
How do I style a child element inside a CSS Module?
You can use descendant selectors in the module file, but the child element must also have a class that gets hashed. For example, .parent .child { color: red; } works if both parent and child are defined in the same module and applied to the elements.
Can I use CSS Modules with Sass or Less?
Yes, you can preprocess the module file with Sass or Less before the CSS Modules transformation. In webpack, use sass-loader before css-loader. The class names still get hashed.
How do I override a CSS Module style from a parent component?
You cannot directly target a hashed class from another module. Instead, pass a className prop to the child component and apply it alongside the module’s class. Alternatively, use CSS custom properties (variables) to allow theming.
Are CSS Modules the same as scoped CSS in Vue?
No, Vue’s scoped CSS adds a data attribute to elements and compiles selectors to include that attribute. CSS Modules hash class names. Both achieve scoping, but the implementation differs. Vue also supports CSS Modules if you prefer.
What happens if I use a global selector inside a CSS Module?
By default, all selectors in a module are scoped. To intentionally target a global element, wrap it in :global(...). For example, :global(.navbar) { ... } will not be hashed.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Gmail Notifications Not Working? Fixes That Work
- Fix Thumbnails Not Showing on Network Drives in Windows 11
- Stop Skype Auto-Start in Windows: 5 Fixes
- SQL Injection Prevention: Step-by-Step Guide
- Fix Windows PowerShell Popping Up
- Print iMessage or Text Conversations on iPhone & iPad