CSS Modules and CSS-in-JS

Intermediate · 12 min

How CSS Modules hash class names at build time, how CSS-in-JS generates styles from JavaScript, and how to choose between them and the alternatives.

Before thisUtility-first CSS and TailwindCSS architecture and BEM

Harry Wolff · 12 min

CSS Modules and CSS-in-JS

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Harry WolffReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • CSS's core scaling problem is that class names are global. CSS Modules fix it in the build: every class in a `.module.css` file gets a unique generated name, so `.title` in one file cannot collide with `.title` in another.
  • You import a CSS Module as an object and use its keys: `import styles from './Card.module.css'` then `className={styles.title}`. The object maps your names to the hashed ones.
  • `composes` shares rules between classes in modules, and `:global(.name)` opts a single class out of renaming.
  • CSS-in-JS puts styles in JavaScript. Runtime libraries (styled-components, Emotion) build and inject CSS in the browser. Zero-runtime libraries (vanilla-extract, Linaria, Panda CSS) extract static CSS at build time.
  • Runtime CSS-in-JS costs JavaScript size and work during rendering and fits server components poorly, which is why many teams moved to modules, utilities or zero-runtime options.

The root problem: one global namespace

Every class in CSS lives in a single global pool. If two developers independently write .title or .container, their rules merge. BEM solves it with discipline: long, namespaced names that people have to follow. Utility-first CSS avoids naming. A third family lets the build tool handle it, so you can keep writing short names without collisions.

CSS Modules

A CSS Module is an ordinary CSS file with one rule changed: class names are local to the file. The build step renames each class to a unique name, and gives you a mapping.

/* Card.module.css */
.card { border: 1px solid #ddd; }
.title { font-size: 1.25rem; }
.featured { border-color: gold; }
import styles from './Card.module.css';

export function Card({ featured, children }) {
  return (
    <article className={`${styles.card} ${featured ? styles.featured : ''}`}>
      <h2 className={styles.title}>{children}</h2>
    </article>
  );
}

The output CSS contains names like ._u06NG_card, and styles.card equals that string. I ran a file like this through Lightning CSS with cssModules: true and it returned a map of btn and title to hashed names and rewrote the selectors, which is the same job webpack’s css-loader and Vite’s built-in support do.

Two features:

  • composes lets one class include another’s rules: .title { composes: btn; } produces an export where styles.title is two class names joined (the module’s own plus the composed one). I confirmed in Lightning CSS’s output that composes was recorded as a dependency in the export map, not copied into the rule.
  • :global(...) leaves a name unrenamed. It is needed to target classes set outside the module, such as :global(.dark) .card for a theme class on the root.

Because it is plain CSS, everything else works as normal: nesting, custom properties, media queries, animations, and @layer. Rules are local to the component, but they do not stop outside CSS from affecting the component, so specificity and cascade layers still matter.

Other roadmaps cover scoped styles per framework: styling React components, styling Vue components, and Angular’s view encapsulation. The browser’s own version, shadow DOM, is in web components in the frontend roadmap.

CSS-in-JS

CSS-in-JS puts the styles inside the component’s JavaScript:

const Title = styled.h2`
  font-size: 1.25rem;
  color: ${(p) => (p.$featured ? 'goldenrod' : 'inherit')};
`;

The library creates a class name, writes the CSS into a <style> tag, and applies it. Styles can use props and JavaScript values directly, which is the attraction, and styles are local by construction, like modules.

There are two kinds, which behave very differently:

  • Runtime: styled-components and Emotion run in the browser, building CSS strings while components render and inserting them into the page. Dynamic values are easy. The costs: library size in your bundle, extra work on each render, and a harder time with server rendering (style collection) and streaming.
  • Zero-runtime: vanilla-extract, Linaria and Panda CSS (and Meta’s StyleX) extract static CSS during the build, so the browser receives a stylesheet and class names, as with CSS Modules. Dynamic values are limited to what can be expressed through variables or variants.

Runtime libraries fit poorly with React Server Components, which have no browser-side runtime to inject styles, and that was a major reason for the shift away. The Better Stack video in further viewing, “RIP Styled Components… What Now?” (April 2025), says that styled-components’ maintainers announced it was entering maintenance mode and links their announcement; I have not read the announcement myself. The npm registry, though, lists 7.0.0 prereleases published in early November 2026, so the project is not dormant today. Treat that video as the state of things in spring 2025 and check the project’s current status before betting on it.

Choosing

If you value Consider
Writing plain CSS with local scope CSS Modules
A shared design scale and rapid iteration Utility-first (Tailwind)
Styles that depend heavily on JavaScript values, with build-time extraction Zero-runtime CSS-in-JS
An existing runtime CSS-in-JS app Keep it, and plan around server rendering costs
Framework-native scoping The framework’s own (Vue and Svelte scoped styles, Angular encapsulation)

None of these changes the CSS you write inside them: specificity, the cascade and layout all work the same. A team that understands those can move between approaches.

What the video covers

Harry Wolff’s “CSS Modules: Why are they great?” (November 2019, about 12 minutes) is part 2 of a series on styling and describes what CSS Modules are and why to use them, with a link to the CSS Modules repository. It is from 2019 and from a smaller channel, about 27 thousand subscribers, so its tooling setup may have changed, while the mechanism it describes (local names by default) has not. I could not read a transcript, so which framework it demonstrates is not described here. The runtime versus zero-runtime split and the Lightning CSS test come from documentation and my own run. Fireship’s survey of seven ways to write CSS in React (2022) is in further viewing.

Where this fits

This is the second answer to the problem set by CSS architecture, alongside Tailwind. The next lesson steps back from authoring to inspection: debugging CSS with DevTools.

Check yourself

  1. 01Two files each define `.title`. In plain CSS what happens, and what happens with CSS Modules?

    In plain CSS both rules apply to every `.title` on the page, so the stylesheet loaded last or the more specific one wins and styles leak across components. With CSS Modules each file's `.title` is renamed to something unique such as `_title_u06NG`, and the import gives each component its own mapping, so neither affects the other.

  2. 02What does `:global(.dark) .card { ... }` do inside a CSS Module?

    `.card` is local and gets renamed. `:global(.dark)` is left exactly as written, so the rule matches a locally named card inside an ancestor with the real, unhashed class `dark`. It is the escape hatch for classes set by outside code, like a theme class on `<html>`.

  3. 03Why do runtime CSS-in-JS libraries have trouble with React Server Components?

    They create styles by running JavaScript in the browser, using React context and effects to inject style tags. Server components have no client-side runtime or context, so the library's work cannot run there. Zero-runtime libraries and CSS Modules produce plain CSS ahead of time, which works anywhere.

  4. 04What is one reason to still choose CSS Modules over utility classes?

    You write ordinary CSS, with full access to selectors, nesting, animations and custom properties, and the build handles scoping. Designers and developers who prefer a stylesheet to long class lists, or teams with existing CSS, can migrate component by component.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark