What are CSS Modules in Next.js?
CSS Modules are .module.css (or .module.scss) files whose class names are scoped to the component that imports them. Next.js compiles each class into a unique name, so styles never leak or collide, with zero runtime cost.
How they work
import styles from "./button.module.css" returns an object mapping your class names to generated ones, for example styles.primary becomes button_primary__x7a2c. Only the CSS for modules actually imported on a route is loaded.
Rules and features
- Use class selectors. A bare element selector like
button { }is not "pure" and is rejected, because it would be global. - Use
:global(.some-class)to target a global class from inside a module. composeslets one class reuse another:.danger { composes: base; color: red; }.- Class names with dashes are accessed with brackets:
styles["is-active"]. - They work in both Server and Client Components because they are just static CSS.
Why choose them
- No runtime cost, unlike runtime CSS-in-JS libraries. That matters in Server Components, which cannot use runtime style injection.
- Plain CSS skills apply.
- Pairs well with design tokens in CSS variables.
Compared to Tailwind
Tailwind puts utilities in markup; CSS Modules keep styles in a separate file. Both are recommended for the App Router, and many teams use Tailwind for layout and CSS Modules for complex components.
TypeScript
Next.js types *.module.css imports as { readonly [key: string]: string }. For typed class names, use a plugin such as typescript-plugin-css-modules.
Code example
1/* app/components/button.module.css */2// .base { padding: 0.5rem 1rem; border-radius: 0.5rem; font-weight: 600; }3// .primary { composes: base; background: var(--brand); color: white; }4// .ghost { composes: base; background: transparent; }5// .wrapper :global(.icon) { margin-right: 0.25rem; }67// app/components/button.tsx8import styles from "./button.module.css";910type Props = {11 variant?: "primary" | "ghost";12 children: React.ReactNode;13};1415export function Button({ variant = "primary", children }: Props) {16 // styles.primary -> "button_primary__x7a2c" (unique per file)17 return (18 <span className={styles.wrapper}>19 <button className={styles[variant]}>20 <i className="icon">★</i>21 {children}22 </button>23 </span>24 );25}
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 Next.js set.