Styling with CSS Modules

Write plain CSS scoped to each component, with no runtime cost and full access to modern CSS features.

Intermediate · about 4 hours · difficulty 2/5

Learn first: React Fundamentals

CSS Modules keep styles in normal .module.css files, but class names are scoped to the component that imports them. Both Vite and Next.js support them with no setup.

How it works

You write .card { ... } in Card.module.css, import styles from it, and use className={styles.card}. At build time the class becomes a unique name, so two components can both have a .title class without clashing.

Why choose it

  • You write real CSS, so everything you learned (Grid, custom properties, container queries) applies directly.
  • Clear separation between markup and styles, which some teams prefer for large components.
  • Zero runtime cost and good compatibility with server components.

Working well with it

  • Put shared design tokens (colours, spacing) in global CSS custom properties and reference them in every module.
  • Use composes or a shared utility module for repeated patterns.
  • Keep one module per component, next to the component file.

Pitfalls

  • Duplicating colours and spacing values in every file instead of using tokens.
  • Overusing global styles, which defeats the point of scoping.
  • Deep selector nesting that is hard to override.

You are ready to move on when you can style your internship board with CSS Modules and shared tokens, and explain how scoping prevents class name collisions.

Key concepts

  • Scoped class names
  • Global tokens with custom properties
  • composes and shared modules
  • Responsive styles in modules
  • Conditional classes
  • Sass with modules

Other options for this step

  • Styling with Tailwind CSS: Style React components quickly and consistently with utility classes, a shared design scale and component patterns.

Mini project

Build a small design system for your board using CSS Modules: tokens in a global file, Button, Card and Badge modules, and a dark theme driven by a data attribute.

Check yourself

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

Free resources