Styling Next.js: CSS Modules, Tailwind, and Tokens
Next.js has no opinionated styling layer, and that freedom is both the appeal and the trap. The framework guarantees that global CSS will not leak between routes, supports CSS Modules out of the box, and compiles modern syntax like nesting and container queries with lightningcss â but it will not stop a team from mixing four styling systems across three years of pull requests. Choosing deliberately, and enforcing the choice with a shared token layer, is what keeps a codebase legible.
This lesson compares the major approaches in App Router terms â where each file lives, how it interacts with Server and Client Components, and what it costs at runtime â then shows how design tokens tie everything together and how to migrate without a big-bang rewrite.
Prerequisites
- !Basic HTML and CSS
- !Next.js App Router project structure
- !Familiarity with React component composition
What You'll Learn
- 1Place global styles and CSS Modules correctly in the app directory
- 2Use Tailwind utilities without shipping redundant CSS
- 3Evaluate CSS-in-JS options under React Server Components
- 4Define and consume design tokens as CSS variables
Where styles live in the App Router
The root layout imports globals.css, and anything defined there applies site-wide. Component-scoped styles come from .module.css files that the build hashes into unique class names. Both work in Server Components because they compile to plain CSS; neither needs a client boundary.
// app/globals.css
:root {
--color-brand: #2563eb;
--color-brand-dark: #1d4ed8;
--color-surface: #ffffff;
--radius-md: 0.5rem;
--space-4: 1rem;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: system-ui, -apple-system, sans-serif;
color: #0f172a;
background: var(--color-surface);
}
/* component styles live in their own module files, shown next */
/* components/Button.module.css */
.button {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border: none;
border-radius: var(--radius-md);
background: var(--color-brand);
color: white;
font-weight: 600;
cursor: pointer;
}
.button:hover {
background: var(--color-brand-dark);
}
.button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
// components/Button.jsx
import styles from './Button.module.css';
export default function Button({ children, disabled, onClick }) {
return (
<button className={styles.button} disabled={disabled} onClick={onClick}>
{children}
</button>
);
}
The hashed class name means two components can both define .button without collision. Composition also works: composes: base from './base.module.css'; pulls shared rules in without duplicating them. A useful convention is to name module files after the component they style and keep selectors flat â one class per element â so the specificity graph stays shallow and overriding a rule in a later sprint does not require !important.
Tailwind without the baggage
Tailwind generates utilities on demand by scanning your source files, so a component that uses four utilities ships four rules, not the whole framework. In Next.js the PostCSS plugin runs during next build, and the globals.css file simply contains the three layer directives. The App Router wrinkle is client components: a file marked 'use client' that uses dynamic class names built at runtime will fool the scanner, so prefer complete class strings or safelist patterns for anything constructed dynamically. Keeping a lint rule that flags string-built class names catches this before production CSS comes up short.
// components/ProductCard.jsx
export default function ProductCard({ product }) {
return (
<article className="rounded-2xl border border-slate-200 p-6 shadow-sm transition-shadow hover:shadow-lg">
<h3 className="mb-2 text-lg font-semibold text-slate-900">{product.name}</h3>
<p className="mb-4 text-sm text-slate-600">{product.blurb}</p>
<div className="flex items-center justify-between">
<span className="text-xl font-bold text-brand">{product.price}</span>
<button className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-dark">
Add to cart
</button>
</div>
</article>
);
}
Arbitrary values such as mt-[13px] are a useful escape hatch and a smell in quantity. When a file accumulates several, the value probably deserves a token.
CSS-in-JS under React Server Components
Styled-components and Emotion require a runtime that reads a context and injects styles, which means the component must run in the browser. In the App Router that forces 'use client' on anything styled that way, pulling its whole import tree into the client bundle. The styled-jsx support built into Next.js has the same constraint for dynamic styles. If you are starting fresh, plain CSS Modules or Tailwind avoid the boundary problem entirely; if you are migrating, isolate CSS-in-JS behind client leaf components while the rest of the tree converts.
The comparison that matters in practice
| Approach | Server Components | Runtime cost | Scoping | Team ergonomics |
|---|---|---|---|---|
| Global CSS | Native | None | Manual prefixes | Simple, easy to rot |
| CSS Modules | Native | None | Automatic | Strong; best default |
| Tailwind | Native | Build-time only | Utility discipline | Fast once learned |
| styled-components / Emotion | Requires client boundary | Hydration + runtime | Automatic | Familiar, heavier |
For most product teams the pragmatic combination is Tailwind for layout and spacing plus CSS Modules for genuinely complex component CSS, both consuming the same tokens. Whatever you pick, write it down in the repository â a short ADR or README section â so the next engineer adds to the system instead of around it.
Design tokens are the glue
Tokens are named values â colors, spacing steps, radii, font sizes â declared once and consumed everywhere. In a framework-agnostic form they are CSS custom properties on :root or a data-theme attribute. Tailwind maps them through theme.extend, CSS Modules reference them with var(), and the result is a single edit that re-themes the product instead of forty scattered hex codes.
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: 'var(--color-brand)',
'brand-dark': 'var(--color-brand-dark)',
surface: 'var(--color-surface)',
},
borderRadius: {
md: 'var(--radius-md)',
},
},
},
};
Dark mode slots into the same pattern: flip the custom properties under a data-theme="dark" selector, and both Tailwind utilities and Module rules follow without a second style sheet.
Migrating without a freeze
Big-bang restyles fail because they touch every file at once and fight every open pull request. A safer sequence is: inventory what exists, agree on tokens, retrofit globals and primitives like buttons and inputs, then convert route by route. Lint rules that ban new styled-components imports stop the bleeding while the conversion proceeds. Each converted route can ship behind its own PR, and the token layer means the visual result stays consistent even when the underlying mechanism changes.
Production pitfalls
The failures are rarely aesthetic. Unstyled flash appears when critical CSS is not in the initial HTML â usually because styles were injected by a client-only library. Duplicate Tailwind installs produce bloated CSS when two versions end up in the lockfile. !important utility sprinkles quietly override component states. And a globals.css file that grows past a thousand lines becomes the dumping ground nobody wants to own, which is the signal that component-scoped files are not being used enough.
Component patterns that keep styles predictable
Whatever mechanism you choose, a few structural patterns prevent the usual decay. Variant props beat conditional class soup: a button component should expose intent â size, tone, state â and map those to class names in one place, whether that map is a Tailwind cva-style helper, a lookup table of Module class names, or both. State-driven styling belongs on real state attributes such as data-state and aria-pressed so a single selector block styles the active case instead of JavaScript concatenating strings. And responsive behavior should live in the stylesheet or utility layer, not in JavaScript resize listeners, because CSS is evaluated on the compositor thread and survives orientation changes, print styles, and split-screen windows that JS listeners handle poorly. The test of a styling architecture is not the first sprint; it is sprint twenty, when a designer asks for a new density mode and the team can answer with a token swap rather than a search-and-replace across two hundred files. Every structural decision above is chosen to make that afternoon short.
Common Mistakes
Marking a whole page 'use client' so styled-components can render
Fix: Keep the page on the server and confine CSS-in-JS to client leaf components, or switch those components to Modules or Tailwind.
Building Tailwind class names dynamically from variables
Fix: Use full literal class strings or safelist the dynamic patterns so the scanner includes them in the build.
Hard-coding brand colors in each component file
Fix: Declare them once as CSS variables and reference via tokens in both Modules and Tailwind config.
Importing a second copy of Tailwind or PostCSS plugins in a subdirectory
Fix: Keep a single root configuration; nested configs silently double the generated CSS.
Best Practices
- Define spacing, color, and radius tokens before writing component styles
- Prefer CSS Modules for anything beyond a handful of utilities, and keep files small
- Co-locate a component's styles with the component so reviewers see both in one diff
- Add a lint rule that flags new CSS-in-JS imports while the codebase standardizes
Interview Questions
Q1: Why do CSS Modules work in Server Components but styled-components does not?
CSS Modules compile to static hashed CSS shipped as files, needing no runtime. styled-components needs a client-side runtime to read context and inject styles, so it forces a client boundary.
Q2: How do design tokens help more than a color constant file?
Tokens live in CSS custom properties, so they can be swapped for theming at runtime and are consumed by any styling mechanism â Tailwind, Modules, or plain CSS â without recompilation.
Q3: What causes unstyled flashes in production?
Styles that only exist after client hydration. Inlining critical CSS or sticking to build-time CSS eliminates the gap.
Key Takeaways
- The App Router runs global CSS and CSS Modules on the server with zero runtime cost; CSS-in-JS forces client boundaries.
- Tailwind ships only the utilities you write, but dynamic class construction needs safelisting.
- Design tokens as CSS variables unify every styling approach and enable dark mode with one attribute flip.
- A hybrid of Tailwind for layout and Modules for complex component CSS covers most teams' needs.
- Migrate route by route behind lint guards instead of freezing the codebase for a restyle.