100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Web

CSS Modules

BeginnerTechnique12.1K learners

CSS Modules is a technique where CSS class names are scoped locally to the component that imports them by default, preventing global naming collisions in larger applications.

Definition

CSS Modules is a technique where CSS class names are scoped locally to the component that imports them by default, preventing global naming collisions in larger applications.

Overview

In a regular stylesheet, all class names live in one global namespace, which means two developers can accidentally reuse the same class name and unintentionally override each other's styles. CSS Modules solves this by treating a file like `Button.module.css` as a module: build tooling rewrites each class name to a unique, generated identifier at build time, and the JavaScript or TypeScript file that imports it receives an object mapping the original class names to those generated ones (e.g. `styles.button`). This scoping happens automatically without requiring a naming convention or discipline from developers, unlike approaches such as BEM that scope classes manually through naming. CSS Modules still lets developers write ordinary CSS — including Sass if compiled through a preprocessor — so there's no new styling syntax to learn, only a change in how class names resolve. Support for CSS Modules is built into most modern front-end tooling, including Vite (web) and Webpack, making it a common choice for teams that want the simplicity of writing plain CSS files with the safety of automatic scoping, as an alternative to CSS-in-JS libraries like styled-components or Emotion CSS.

Key Concepts

  • Automatic local scoping of class names, generated uniquely per file
  • Plain CSS syntax with no new styling language to learn
  • Works with CSS preprocessors like Sass or Less
  • Native support in modern bundlers such as Vite and Webpack
  • composes keyword for sharing styles between class selectors
  • Avoids the runtime overhead associated with some CSS-in-JS libraries

Use Cases

React, Vue, or other component-based apps wanting scoped styles without CSS-in-JS
Large codebases where global CSS class name collisions have become a problem
Teams that prefer writing plain CSS files over JavaScript-embedded styles
Migrating an existing plain-CSS codebase toward safer, component-scoped styling
Design systems wanting predictable, debuggable CSS output without a CSS-in-JS runtime

Frequently Asked Questions

From the Blog