HTML & CSSMedium
What are CSS Modules?
CSS Modules are CSS files in which every class name is scoped locally by default: at build time, .button in Button.module.css is renamed to a unique hash like Button_button__x7f2a, and you import the generated names as a JavaScript object (styles.button). This gives component-level isolation with plain CSS and zero runtime cost.
How it works
/* Button.module.css */
.button { padding: .5rem 1rem; }
.primary { background: #2b4bff; color: white; }
import styles from "./Button.module.css";
<button className={`${styles.button} ${styles.primary}`}>Save</button>
- The bundler (Vite, webpack, Turbopack, which Next.js uses) generates unique class names and a mapping object.
- Supported out of the box in Next.js, Vite and Create React App.
Features
:global(.dark) .button { ... }targets global classes.composes: base from "./shared.module.css";reuses another class.- Works with Sass (
.module.scss) and PostCSS. - TypeScript types can be generated for autocomplete on
styles.*.
Pros
- No naming conventions needed (no BEM), no collisions between components.
- Plain CSS: media queries, pseudo-classes, animations, nesting.
- Static extraction, so no runtime cost, unlike runtime CSS-in-JS (styled-components, Emotion), which is problematic with React Server Components.
- Dead styles are easy to find and delete per component.
Cons
- Theming across components needs CSS custom properties.
- Class names are less readable in DevTools (configurable in development).
- Dynamic styles need
styleprops or custom properties.
Interview tip
Compare CSS Modules, Tailwind and CSS-in-JS on scoping, runtime cost and Server Component compatibility.
Code example
tsx
1/* Button.module.css */2.button {3 padding: 0.5rem 1rem;4 border: 2px solid #0b1020;5 border-radius: 8px;6 font-weight: 700;7 background: white;8}9.primary { background: var(--brand, #2b4bff); color: white; }10.button:focus-visible { outline: 3px solid #ffd84d; }11:global(.dark) .button { border-color: white; }1213// Button.tsx14import styles from "./Button.module.css";1516type Props = { variant?: "primary" | "default"; children: React.ReactNode };1718export function Button({ variant = "default", children }: Props) {19 const className = [styles.button, variant === "primary" && styles.primary]20 .filter(Boolean)21 .join(" ");22 return <button className={className}>{children}</button>;23}2425// Rendered HTML (class names are hashed and unique):26// <button class="Button_button__x7f2a Button_primary__q91kd">Save</button>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.