CSS Modules

Write normal CSS files whose class names are scoped to one component automatically, with zero runtime cost.

Beginner · about 3 hours · difficulty 2/5

Learn first: Custom Properties and Modern CSS Features, Build Tools and Bundlers

CSS Modules keep plain CSS but fix its biggest problem at scale: global class names. When you import Button.module.css into a component, the build tool rewrites .primary into something unique like Button_primary__x7f2a, so two components can both use .title without colliding.

How it works

import styles from "./Card.module.css";
<div className={styles.card}>...</div>

Vite, Next.js and most bundlers support CSS Modules with no configuration. Each file is its own scope; use :global(...) sparingly when you really need to reach outside.

Strengths

  • You write real CSS: every feature (grid, container queries, nesting, custom properties) works as-is.
  • No runtime library, so no performance cost and full compatibility with Server Components.
  • Styles are deleted along with the component that imports them.

Patterns

  • Keep one module per component, named after it.
  • Use custom properties for theming and pass dynamic values through style={{ "--progress": value }}.
  • Combine classes with a small helper such as clsx.
  • Share design tokens through a global tokens.css of variables, not by importing other modules.

Pitfalls

Composition across files (composes:) can get tangled, and you still need your own spacing and colour scale discipline. TypeScript needs a small declaration or plugin to type the imported class names.

Good enough to move on

You can style a component library of 5 to 10 components with CSS Modules, theme them via variables, and explain how the class name scoping is generated.

Key concepts

  • Local scoping and generated class names
  • Importing modules into components
  • :global escapes
  • Theming with custom properties
  • composes and sharing styles
  • Typing class names in TypeScript

Other options for this step

  • Tailwind CSS: Utility-first styling that keeps design decisions consistent and colocated with markup; our recommended default for new projects.
  • Sass and Preprocessors: Variables, nesting, mixins and partials compiled to CSS; still common in existing codebases even though native CSS has caught up.
  • CSS-in-JS: Style components with JavaScript (styled-components, Emotion) or zero-runtime tools (vanilla-extract, Panda); know the trade-offs.

Mini project

Create Button, Card, Badge and Modal components styled with CSS Modules, themed by a global tokens.css, and verify in DevTools that class names are scoped.

Check yourself

Two components both define a .title class in their own module file. Why do they not conflict?

Free resources