🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Scoped Styles with CSS Modules in Next.js

Next.js StylingđŸŸĸ Free Lesson

Scoped Styles with CSS Modules in Next.js

CSS Modules are the quietest styling option in Next.js: no runtime, no configuration file, no class name collisions, and a build step that has been part of the toolchain since the pages directory existed. The entire mechanism is one transform. Every selector in a file named Card.module.css is rewritten at build time into a unique string — .card_x3f1a_1 — and the imported object maps your original names to those hashed ones. The browser never sees .card, so two components can both define .card and never touch each other.

That hash is the whole feature, and it also explains the constraints people trip over: global styles leak, dynamic class names cannot be constructed by hand, and composition works differently than inheritance in a preprocessor.

Prerequisites

  • !Basic CSS selectors and the cascade
  • !Importing and exporting objects in JavaScript
  • !A Next.js project using the app directory

What You'll Learn

  • 1Explain how a .module.css file becomes scoped class names
  • 2Compose and extend styles with the composes declaration
  • 3Separate global resets from component styles correctly
  • 4Build dynamic variant classes without string interpolation bugs

What scoping actually means

Create components/Card.module.css and Next.js treats every class selector in it as local. Import the file and you get an object whose keys are the class names you wrote:

/* components/Card.module.css */
.card {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  padding: 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.75rem;
  background: #ffffff;
}

.cardHeader {
  font-size: 1.125rem;
  font-weight: 600;
  letter-spacing: -0.01em;
}

.cardBody {
  color: #475569;
  line-height: 1.6;
}

.primary { border-left: 4px solid #2563eb; }
.success { border-left: 4px solid #16a34a; }
.danger  { border-left: 4px solid #dc2626; }

@media (min-width: 48rem) {
  .card { padding: 1.5rem; }
}
// components/Card.jsx
import styles from './Card.module.css';

export default function Card({ variant = 'default', title, children }) {
  const classes = [
    styles.card,
    variant === 'primary' && styles.primary,
    variant === 'success' && styles.success,
    variant === 'danger' && styles.danger,
  ]
    .filter(Boolean)
    .join(' ');

  return (
    <div className={classes}>
      {title && <header className={styles.cardHeader}>{title}</header>}
      <div className={styles.cardBody}>{children}</div>
    </div>
  );
}

Notice what is not there: no styled(Card) wrapper, no context provider, no runtime evaluation of the CSS string. The imported object is a plain JavaScript object created during the build, so styling costs nothing at render time. Media queries, pseudo-classes, and keyframes inside the module are rewritten the same way as class selectors, which is why an animation name declared in a module does not collide with an identically named animation in another component.

The one thing scoping does not change is specificity. Two hashed classes on the same element still resolve by source order in the stylesheet, and a hashed class does not beat an inline style. Scoping solves naming, not cascade.

It is worth being precise about what the hash contains, because it explains two behaviours you will meet eventually. The generated name carries a hash of the file path and, in dev mode, the line number, which is why moving a file to another folder changes every class string and why hot reload produces a different name than a production build. It also means class names in the DOM are not stable across deploys — anything that persists them, from a visual regression snapshot to a user's saved layout selector, will break on the next release. If you need a stable hook for tests or end-to-end selectors, add a plain data-testid attribute next to the hashed class rather than parsing the class list.

Composes: extension without duplication

CSS has no inheritance between class selectors, so shared behaviour normally means copy-paste or a preprocessor mixin. Modules solve it with composes, which pulls one or more existing classes into the current one:

/* components/base.module.css */
.base {
  font-family: system-ui, sans-serif;
  border-radius: 0.5rem;
  transition: box-shadow 150ms ease, transform 150ms ease;
}

/* components/Button.module.css */
@import './base.module.css';

.button {
  composes: base;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 1.25rem;
  border: 0;
  cursor: pointer;
}

.primary { composes: base; background: #2563eb; color: #fff; }
.ghost   { composes: base; background: transparent; border: 1px solid #cbd5e1; }

The result is not inheritance — the compiled output simply places both hashed class names on the element, so .button renders as className="button_hash ghost_hash". Two rules follow from that. composes can only reference classes (not element or attribute selectors), and it must be written before other declarations inside the rule. Composition across files works too, provided the source file is itself a module.

Globals have one legal home

Nothing stops you from writing body { margin: 0 } in a module file — it will simply not be hashed, because there is no class selector to hash, and it will leak to the entire application. That is why global selectors belong in app/globals.css, imported exactly once from the root layout.

// app/globals.css
*,
*::before,
*::after { box-sizing: border-box; }

html { -webkit-text-size-adjust: 100%; }

body {
  margin: 0;
  font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
  color: #0f172a;
  background: #f8fafc;
}

/* A deliberate, documented global utility */
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
}
// app/layout.js
import './globals.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

Two practical warnings. A CSS file imported by a layout is scoped to that layout's subtree at the CSS layer level only in terms of authoring — once loaded it applies document-wide, so a module imported by a sibling component can still see those globals. And duplicate global imports are deduplicated by the bundler, but importing globals from a deeply nested component makes the load order hard to reason about; keep the import at the root.

Dynamic classes must come from the object

The most common runtime bug is building a class name with string concatenation. Because the real class contains a hash you cannot predict, looking up styles[variant] works while constructing a name from a prefix and the variant never will — the result is a string that exists nowhere in the stylesheet, so the element renders completely unstyled while every other check passes.

// Correct: every class referenced statically, looked up by key
import styles from './Alert.module.css';

const TONE_CLASS = {
  info: styles.info,
  warning: styles.warning,
  error: styles.error,
};

export function Alert({ tone = 'info', children }) {
  // Unknown tone still renders a valid, styled element.
  const toneClass = TONE_CLASS[tone] || styles.info;
  return <p className={`${styles.alert} ${toneClass}`}>{children}</p>;
}

The lookup table is worth keeping even if you only have three tones. It documents which variants exist, gives TypeScript something to check against when you add a styles.d.ts declaration, and guarantees that a class appears in the final CSS — because a class never referenced in source is never emitted by the build. That last point cuts the other way too: a variant you only ever assign dynamically will be missing from the stylesheet unless some file references it statically.

Structuring the file once the component grows

A card with three variants is easy. The same card with three variants, a density setting, three states, and a dark theme is where flat files start to sprawl, and the file itself needs an order. The convention that holds up in real codebases reads top to bottom like a description of the element: base shape, layout, typography, tones, states, responsive overrides, and finally keyframes.

/* components/TableRow.module.css — ordered by concern */
.row {
  display: grid;
  grid-template-columns: 2rem 1fr auto;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--line);
  color: var(--ink);
}

.compact { padding: 0.375rem 1rem; }

.row:hover,
.row:focus-visible {
  background: color-mix(in srgb, var(--surface) 6%, transparent);
}

.row[aria-disabled='true'] {
  opacity: 0.5;
  pointer-events: none;
}

.row.is-selected {
  box-shadow: inset 3px 0 0 var(--brand);
}

@media (max-width: 48rem) {
  .row { grid-template-columns: 1fr auto; }
}

Three details in that file pay for themselves. Every colour comes from a custom property, so a theme switch or a high-contrast mode never touches this component. Aria attributes carry state — aria-disabled and aria-selected — so the visual state and the accessibility tree stay in agreement instead of drifting apart. And the responsive override sits last, where it is obvious which rules it wins over, rather than being buried between two unrelated selectors.

When a module passes roughly sixty lines or starts mixing unrelated concerns, split it by responsibility — TableRow.module.css for the element and TableRowStates.module.css for the state machine of classes — rather than by feature. Two small files with clear names beat one large file that nobody scrolls to the end of.

Modules versus the alternatives

ConcernCSS ModulesTailwind utilitiesCSS-in-JS
Runtime costNoneNoneStyles computed in the browser
Name collisionsPrevented by hashingShared vocabulary by designScoped by generated selectors
Dynamic valuesNeeds a class per variantNeeds arbitrary values or inline styleTrivial, props become styles
ColocationOne file per componentIn the markupIn the component file
Server renderingCompiled ahead of timeCompiled ahead of timeRequires a streaming SSR setup

Choose modules when you want real CSS — cascade, media queries, pseudo-elements — with isolation and no JavaScript on the path. Choose utilities when the team prefers reading layout in the markup. Reach for CSS-in-JS only when styles genuinely depend on runtime props, and even then inline style often covers it.

Common Mistakes

Building class names with template strings

Fix: Reference styles.name statically or look the variant up on the imported object; a constructed name will never match the hashed output.

Writing element selectors inside a .module.css file

Fix: Only class selectors are scoped. Move element or attribute selectors to globals.css, or wrap them in a class you own.

Assuming a module import limits where the CSS applies

Fix: Scoping renames selectors; it does not create a style boundary. Globals still apply to the whole document once loaded.

Defining a variant only through a dynamic expression

Fix: The build only emits classes it can see. Reference each variant statically in a map so the rule lands in the stylesheet.

Best Practices

  • Keep one module per component and name the file after the component
  • Put resets and the handful of true globals in app/globals.css only
  • Build small composes-based bases rather than deep composition chains
  • Generate a styles.d.ts file so typos in class names become type errors

Key Takeaways

  • Next.js hashes every class selector in a .module.css file, so identical names in different files never collide.
  • Importing a module gives you a plain object; styling costs nothing at runtime.
  • composes copies classes into the output rather than inheriting, and only works on classes declared before other rules.
  • Global selectors are never hashed — author them in globals.css, imported once by the root layout.
  • Dynamic class names must be looked up on the imported object, and every variant needs a static reference to be emitted.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement