skip to content

CSS Modules

A .module.css file hashes its class names per file and gives JavaScript a map of them, with composes to reuse a class and :global to opt out. Interviewers probe what the scoping does not stop.

on this pageshow

questions

5

In a CSS Modules setup, what does `import styles from './BookCard.module.css'` give a component, and why do two files' `.title` classes stop clashing?

level: juniorimportance: must knowfreq 30%

answer

  1. names rewritten at build time
  2. authored name to generated name
  3. file path feeds the generated name
  4. class, ID and keyframes names
  5. plain object of strings

basics

~20 s

An object mapping each class name written in the file to a generated name unique to that file. The build rewrites the CSS to the generated names, so two files' .title become two different classes.

solid answer

~40 s

A CSS Modules file is **local by default**: at build time the transform rewrites every class name, ID and `@keyframes` name not marked `:global` to a generated name derived from the file (its path, a hash, or both), emits ordinary global CSS with those names, and hands JavaScript a **class map** — a plain object such as `{ title: 'BookCard_title__k3x9' }`. The component applies `styles.title`, never the literal `title`. Because `Header.module.css` and `BookCard.module.css` each get their own generated name for `.title`, the two rules no longer target the same class. Nothing is isolated at runtime: the browser just sees two differently named global classes.

go deeper

for a junior

Say what the import returns — an object from your class name to a generated one — and why two files' identical class names stop colliding.

for a middle

Explain the two outputs of the transform, which names get rewritten (classes, IDs, keyframes) and which stay global, and that the map is a plain object of strings.

for a senior

Show where the naming guarantee ends: element selectors, descendant reach and global opt-outs, plus why the generated-name pattern must be deterministic across server and client builds.

for a principal

Frame the generated-name pattern as a policy decision for a shared codebase: debuggability against size, collision risk against hash length, and one pattern pinned across every build that renders the same markup.

## What the import actually returns A **CSS Module** is a CSS file in which class names and animation names are **scoped locally by default**. You write ordinary CSS: ```css /* BookCard.module.css */ .title { font-weight: 600; } .cover { aspect-ratio: 2 / 3; } ``` and the build turns that one file into **two outputs**: 1. **CSS** — the same rules, but with each local name replaced by a **generated name**, for example `.BookCard_title__k3x9`. This CSS is normal, global CSS: it is injected into the page or concatenated into a stylesheet. 2. **Data** — a JavaScript object, the **class map**, from the name you wrote to the name that was generated: `{ title: "BookCard_title__k3x9", cover: "BookCard_cover__p01q" }`. `import styles from './BookCard.module.css'` gives you the second output. The component writes `className={styles.title}`; the string it receives is the generated name, which is the only name the emitted CSS uses. ## Why two `.title` classes no longer clash Without the transform every class lives in one page-wide namespace, so a later `.title` rule overrides an earlier one wherever both match. With CSS Modules, the generated name is computed **per file**: - the transform's default naming function builds it from the sanitised file path plus the local name; - toolchains typically add a short hash of the path and name, so even files with the same basename differ; - `Header.module.css` and `BookCard.module.css` therefore produce two distinct names for `.title`, and each component only ever applies its own. The scoping is a **naming convention enforced by a compiler**. Nothing runs in the browser to isolate styles; there is no shadow root and no wrapper selector. The browser simply receives two classes that happen never to share a name. ## Which names are rewritten | Written in the module | Rewritten? | Note | |---|---|---| | `.title` (class) | yes | the common case | | `#results` (ID) | yes | IDs are localised like classes | | `@keyframes coverFlip` | yes | and `animation` / `animation-name` references in the file are rewritten to match | | `img`, `[data-state]`, `*` | no | element, attribute and universal selectors stay global | | `:global(.is-modal-open)` | no | an explicit opt-out | The last two rows are where "scoped" stops being true, which interviewers like to probe. ## The generated-name pattern is a trade The naming pattern is configurable, and the choice is a trade between debuggability and size: - a **readable** pattern such as `[path][name]__[local]` shows in DevTools which file and class a rule came from — the webpack css-loader README recommends it for development; - a **short hash** such as `[hash:base64]` keeps HTML and CSS smaller and is that README's production recommendation; - a pattern **without** any file-specific part (only `[local]`) reintroduces the clashes the technique exists to prevent, and a very short hash raises the odds of a collision. The generated name must also be **deterministic**: when a page is rendered on a server and hydrated in the browser, both builds have to compute the same name for the same file and class, or the markup's classes will not match the stylesheet's. ## What the map is, and is not - It is a **plain object of strings**. A key that does not exist evaluates to `undefined`; nothing throws. - A class that **composes** another maps to a space-separated list of generated names, so one key can apply several classes. - Global names written with `:global` are **not** in the map by default. - The map carries no declarations — it is not a style object for inline styles. Under the hood, CSS Modules compile to a low-level format called **ICSS** (Interoperable CSS); the class map is literally an `:export` block the transform appends to the CSS, which the loader turns into the JavaScript object. ## Common misreadings in interviews - **"The styles are encapsulated."** Only the names are. A rule in a module can still reach any element that matches it, which is why element selectors and deep descendant selectors in module files deserve review. - **"The generated names are random."** They are computed from the file and the class name, so the same build produces the same names; that determinism is what lets server-rendered markup and the client's stylesheet agree. - **"The map tree-shakes unused CSS."** The map lists every local class in the file; a class no component reads is still emitted in the CSS. - **"It only works with one framework."** The technique is a build transform; implementations exist for many bundlers and frameworks, and the import simply returns an object any JavaScript can read.

  • Does a CSS Module isolate its styles at runtime, the way a shadow root does?
    No. The output is ordinary global CSS with unusual class names. Isolation is a property of the names, decided at build time; any selector that does not rely on a local name, such as an element selector, still applies page-wide, and descendant selectors still reach into nested components.
  • Why would a team use a readable generated-name pattern in development but a short hash in production?
    A pattern like `[path][name]__[local]` tells you in DevTools which file and class produced a rule; a short hash shrinks markup and CSS. Both stay unique per file. What must not change between the server and client builds of one release is the pattern itself, or rendered classes stop matching the stylesheet.

A library network where every branch has a shelf called Fiction: each branch's catalogue records its own shelf code, so a card from one branch never sends you to another branch's shelf. The class map is that catalogue, translating the name you know into the code that is unique to its file.

  • CSS Modules wrap each component's rules in a shadow root.
  • The class map holds the rule's declarations as a style object.
  • Every selector in a module file, including `img`, is scoped to that file.
  • Two modules may not both declare a class called `.title`.
  • Generated names are random on every build, so they cannot be predicted.
open as a page

In CSS Modules, how does `composes` let a Button module's `.primary` reuse `.base`, and what rules limit where and how `composes` may be written?

level: middleimportance: should knowfreq 14%

basics

~20 s

composes copies no declarations: it makes the class map's value for .primary list both generated names, so the element carries both classes. It works only on a single local class selector, before other declarations, and cross-file order is undefined.

open as a page

In a CSS Modules file, how do `:global` and `:local` work, and how do you style a component when a dialog adds `is-modal-open` to body?

level: middleimportance: should knowfreq 12%

basics

~20 s

A class set by code outside the module keeps its plain name, so it must be marked global: :global(.is-modal-open) .catalogue { … } keeps that class unhashed while .catalogue stays local. :local switches back to local scope.

open as a page

With CSS Modules, a file declares `.book-card` but `className={styles.bookCard}` leaves the element unstyled without any error — why, and what fixes it?

level: middleimportance: should knowfreq 18%

basics

~10 s

The class map is a plain object whose keys are the names as written, so styles.bookCard is undefined unless the toolchain converts keys to camelCase. Use styles['book-card'], rename the class, or enable key conversion.

open as a page

After a catalogue app moves to CSS Modules, a BookCard rule `img { border-radius: 8px }` rounds every image site-wide and `.card a` restyles links in nested components — what does CSS Modules scoping not protect?

level: seniorimportance: should knowfreq 9%

basics

~20 s

CSS Modules rename class, ID and keyframes names; they do not limit where a rule reaches. Element selectors stay global, descendant selectors match nested components, order between modules follows load order, and inherited values still flow down.

open as a page