Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 72 ยท Optimization and SEO

Styling in Next.js

Compare the ways to style a Next.js App Router app: global CSS, CSS Modules, Tailwind, Sass and CSS-in-JS, and why runtime CSS-in-JS clashes with Server Components.

Next.js does not force a styling system on you. You can write plain CSS files, use CSS Modules, add Tailwind, bring Sass, or pick a CSS-in-JS library. What the App Router changes is which of these fit well with Server Components. A Server Component has no state, no effects and no browser, so any styling approach that needs those things at run time has to move to the client.

In this lesson you will see each option, where its files go, and what its trade-offs are. Next.js code and configuration are read-only here because the framework cannot run on this site. Two stand-ins run live: a Node program that does what a CSS Module build does to your class names, and a React example showing why scoped names stop styles from leaking.

Pick a way to style

Global CSS One stylesheet for the whole app.
CSS Modules Class names scoped to one component.
Tailwind Utility classes written in your JSX.
Sass Variables and nesting, compiled to CSS.
1 / 2

Global CSS

A global stylesheet applies to every page. By convention it is app/globals.css, and you import it once in the root layout:

TSX
// app/layout.tsx (read-only)
import "./globals.css";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
CSS
/* app/globals.css (read-only) */
:root {
  --brand: #0b6cff;
  --text: #1c1f24;
}

body {
  margin: 0;
  color: var(--text);
  font-family: system-ui, sans-serif;
}

a {
  color: var(--brand);
}

Put resets, CSS variables, base typography and element defaults here. You can technically import a global stylesheet from any layout or page, but it stays loaded and active once it is on the page, so keep global CSS in the root layout where its reach is obvious.

Global CSS is a poor place for component styles. A class called .title in one file will fight with every other .title in the app. That problem is what CSS Modules solve.

CSS Modules

A file named something.module.css is a CSS Module. At build time every class name inside it is rewritten to a unique one, and the import gives you an object that maps your original names to the generated ones.

CSS
/* app/ui/button.module.css (read-only) */
.button {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  border: 0;
}

.primary {
  background: var(--brand);
  color: white;
}
TSX
// app/ui/button.tsx (read-only)
import styles from "./button.module.css";

export function Button({ children, primary }: { children: React.ReactNode; primary?: boolean }) {
  const className = primary ? `${styles.button} ${styles.primary}` : styles.button;
  return <button className={className}>{children}</button>;
}

CSS Modules need no JavaScript at run time, so they work in Server Components, Client Components and shared components alike. Some details to know:

  • Selectors must be pure: each selector needs at least one local class or id. A rule like h1 { } alone is rejected in a module; put element rules in the global stylesheet or write .page h1 { }.
  • Use :global(.name) to opt a single class out of renaming.
  • composes: base from "./other.module.css" reuses another module's class.
  • A hyphenated name such as .card-title is read as styles["card-title"], so many teams write class names in camelCase.
  • Conditional classes read better with a small helper such as clsx, instead of template strings.

The stand-in below does what the build does. It takes the text of a CSS Module and a file name, then returns the rewritten CSS and the mapping object that import styles gives you. Real Next.js uses a different hash format and a full CSS parser; this one is a simplified model of the idea.

Node.js What a CSS Module build does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice three things in the output. Decimals such as 0.5rem were not touched, because the rename only applies to selectors. :global(.dark) kept its name. And two modules that both define .button get different generated names, so they cannot collide.

Here is the same idea in the browser. Two components both write a rule for a class called title. Because each one passes its CSS through a scoping function, the rules do not interfere. The unscoped third box shows what happens without scoping: the last stylesheet wins everywhere.

Scoped names stop style leaks

The red and green lines keep their own colors and sizes although both rules were written against .title. In your real project the build does this renaming for you.

Tailwind CSS

Tailwind is a utility-first framework: instead of writing CSS, you compose small single-purpose classes in your markup, such as p-4, text-lg or bg-blue-600. The build scans your files and generates only the CSS for the classes you actually used, so the stylesheet stays small.

create-next-app can set Tailwind up for you (see Creating a Next.js App). With Tailwind 4, the setup is a PostCSS plugin plus one import line:

JavaScript
// postcss.config.mjs (read-only)
const config = {
  plugins: { "@tailwindcss/postcss": {} },
};
export default config;
CSS
/* app/globals.css (read-only) */
@import "tailwindcss";

@theme inline {
  --font-sans: var(--font-inter);
}
TSX
// app/page.tsx (read-only)
export default function Page() {
  return (
    <main className="mx-auto max-w-2xl p-6">
      <h1 className="text-3xl font-bold">Hello</h1>
      <p className="mt-2 text-gray-600 dark:text-gray-300">Utility classes, no extra JavaScript.</p>
    </main>
  );
}

Tailwind is plain class names, so it works everywhere, including Server Components. The @theme block is where you define design tokens, and the --font-sans line above connects the font you loaded in Fonts and Third-Party Scripts to Tailwind's font-sans class. Variants such as dark: and md: handle dark mode and responsive layouts. The cost is long class lists in your markup; the usual remedy is to extract a component, not a custom CSS class.

Sass

If you prefer Sass, install the compiler (npm install --save-dev sass) and use the .scss or .sass extension. Both global files and modules work: name a file button.module.scss to get a scoped Sass module. Extra Sass settings go in next.config.ts:

TypeScript
// next.config.ts (read-only)
import path from "node:path";
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  sassOptions: {
    includePaths: [path.join(process.cwd(), "styles")],
  },
};

export default nextConfig;

Nowadays plain CSS has nesting and variables natively, so the case for Sass is weaker than it used to be, but it remains common in older code bases and design systems. More on this file in Configuring Next.js.

CSS-in-JS and Server Components

Libraries such as styled-components and Emotion let you write styles inside JavaScript. They generate class names and inject <style> tags while your components render. That relies on React features, such as context and hooks, that only exist in Client Components. The consequences in the App Router:

  • You cannot use these libraries' components in a Server Component. Files that use them need "use client" (see Client Components and "use client").
  • For server-rendered HTML to arrive styled, the library needs a registry that collects the generated rules during rendering and inserts them with the useServerInsertedHTML hook; the library's docs describe the setup.
  • The library's runtime ships to the browser, which costs JavaScript, and styles are recomputed on the client.

If you like CSS-in-JS ergonomics, look at zero-runtime tools such as Panda CSS, vanilla-extract or StyleX. They give you a similar authoring style but extract real CSS at build time, so they have no run-time cost and no client-only restriction. Check each project's current Next.js support before adopting it. For a new project, CSS Modules or Tailwind are the lowest-friction choices.

CSS-in-JS in practice: styled-jsx, styled-components and Emotion

Here is what the setup looks like for the three libraries you will meet most. Everything is read-only, because these need a running Next.js app. Whichever you pick, the pattern is the same: the library must be used in Client Components, and a registry component collects the CSS while the server renders and inserts it with useServerInsertedHTML (see the stand-in in Using Material UI and Other Component Libraries for the idea).

styled-jsx

styled-jsx is built into Next.js, so there is nothing to install. You write CSS in a <style jsx> tag inside a component, and the styles are scoped to that component:

TSX
// components/badge.tsx (read-only)
"use client";

export function Badge({ children }: { children: React.ReactNode }) {
  return (
    <span className="badge">
      {children}
      <style jsx>{`
        .badge {
          padding: 2px 8px;
          border-radius: 9999px;
          background: #dbeafe;
        }
      `}</style>
    </span>
  );
}

In the App Router a component with <style jsx> must be a Client Component, and for the styles to be present in the server HTML you add a registry in the root layout. The registry uses useServerInsertedHTML and a StyleRegistry from styled-jsx, in a small "use client" file:

TSX
// lib/styled-jsx-registry.tsx (read-only)
"use client";

import { useState, type ReactNode } from "react";
import { useServerInsertedHTML } from "next/navigation";
import { StyleRegistry, createStyleRegistry } from "styled-jsx";

export default function StyledJsxRegistry({ children }: { children: ReactNode }) {
  const [registry] = useState(() => createStyleRegistry());

  useServerInsertedHTML(() => {
    const styles = registry.styles();
    registry.flush();
    return <>{styles}</>;
  });

  return <StyleRegistry registry={registry}>{children}</StyleRegistry>;
}

Wrap in the root layout with it. styled-jsx is fine for small amounts of component-scoped CSS. For larger design systems, CSS Modules or Tailwind are simpler.

styled-components

styled-components creates real React components that carry their styles. Its registry builds on its own ServerStyleSheet:

TSX
// lib/styled-components-registry.tsx (read-only)
"use client";

import { useState, type ReactNode } from "react";
import { useServerInsertedHTML } from "next/navigation";
import { ServerStyleSheet, StyleSheetManager } from "styled-components";

export default function StyledComponentsRegistry({ children }: { children: ReactNode }) {
  const [sheet] = useState(() => new ServerStyleSheet());

  useServerInsertedHTML(() => {
    const styles = sheet.getStyleElement();
    sheet.instance.clearTag();
    return <>{styles}</>;
  });

  if (typeof window !== "undefined") return <>{children}</>; // in the browser the library handles styles itself

  return <StyleSheetManager sheet={sheet.instance}>{children}</StyleSheetManager>;
}
TSX
// components/card.tsx (read-only)
"use client";
import styled from "styled-components";

export const Card = styled.article<{ $featured?: boolean }>`
  padding: 16px;
  border: 1px solid ${(props) => (props.$featured ? "#2563eb" : "#e5e7eb")};
`;

A few habits help: prefix props meant only for styling with $ (transient props), so they are not forwarded to the DOM, and keep every file that defines or uses a styled component marked "use client". The project also needs compiler: { styledComponents: true } in next.config.ts so that Next.js's compiler handles the library's server rendering correctly (class names stay stable between server and client, avoiding hydration warnings).

Emotion

Emotion is the engine behind Material UI. Used directly, its css prop and styled function need a cache and the same useServerInsertedHTML trick. Because the setup is more involved and changes between releases, follow Emotion's current Next.js guide, or use Material UI's AppRouterCacheProvider, which does the job for Emotion for you. Remember that every runtime CSS-in-JS option adds JavaScript to the browser and does work on each render. If that cost matters to you, look at the zero-runtime tools mentioned above.

Specificity and ordering with CSS Modules

CSS Modules are the safest default because every class name is rewritten to a unique one (.button becomes something like button_primary__x7Qd2), so names never collide across files. But collision-free names do not mean no conflicts. Two rules that both match one element are resolved by the cascade: the rule with higher specificity wins, and when specificity is equal, the rule that comes later in the final CSS wins. With modules, two things surprise people.

1. All module classes have the same specificity. A single class selector scores the same everywhere. So if a shared Button module defines .primary and your page module defines .custom and you put both on one element, the winner depends only on which stylesheet is emitted later, and you do not control that directly. The order follows the order in which modules are imported, but the bundler splits and merges CSS into chunks, and the order of a development build can differ from a production build. Do not rely on it.

2. Overriding from outside needs a deliberate strategy. Pick one of these:

  • Raise specificity on purpose, for example with a compound selector: .card .title (two classes) beats a single .title regardless of order. Do not reach for !important.
  • Use one class per decision, so two classes never set the same property on one element: className={isPrimary ? styles.primary : styles.secondary} instead of both plus an override.
  • Use composes to combine classes of a module in a predictable order: .primary { composes: base; color: white; } makes the final element get both classes and puts the composed one first.
  • Use cascade layers (@layer) to make ordering explicit: styles in a later layer beat styles in an earlier one whatever their specificity. This is why Material UI's enableCssLayer option exists.
  • Use CSS variables as the public API of a component, so callers set --card-accent instead of overriding rules.

CSS Modules also have an escape hatch for global names: :global(.dark) .card { ... } styles a class that is not renamed. Only modules with a pure selector (containing at least one local class or id) are allowed: a bare div { ... } selector is rejected, because it would not be scoped.

The stand-in below calculates specificity for simple selectors and then decides which of several competing rules wins, using specificity first and source order second. It also shows a layer beating a higher specificity.

Node.js Specificity, order and layers: who wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If styles differ between next dev and next build, suspect an order-dependent conflict like case 1. Next.js has an experimental cssChunking option that controls how CSS files are merged (check the current docs for its status); the safest fix is still to remove the order dependence from your CSS, not to tune the bundler. And because your global stylesheet (the globals.css file) is unlayered, it can beat layered library styles; that is a feature if you want your own styles to win.

Inline styles and CSS variables

You can always use the style prop for a one-off dynamic value, such as a progress bar's width. A neat pattern is to pass dynamic data through a CSS variable and keep the rules in a stylesheet:

TSX
// read-only
<div className={styles.bar} style={{ "--progress": `${percent}%` } as React.CSSProperties} />
CSS
/* bar.module.css (read-only) */
.bar {
  width: var(--progress);
}

How styles reach the page

In production, Next.js bundles the CSS of each route separately and loads it with the page, so a visitor downloads the CSS a page needs and not the whole site's CSS. Since stylesheets are loaded in the order of imports, avoid relying on rule order between two modules: if one rule must beat another, make it more specific, instead of hoping for a particular order. Test the production build as well as the dev server when the order matters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a CSS Module do to the class names in a .module.css file?

    The build renames each class to a unique name, so styles from different files cannot collide. The imported object maps your names to the generated ones.
  2. 2. Why does runtime CSS-in-JS such as styled-components not fit Server Components?

    These libraries build styles while rendering using React client features, so components that use them must be Client Components and need a registry for server rendering.
  3. 3. Where should a global stylesheet such as globals.css normally be imported?

    Global CSS affects the whole page once loaded. Importing it in the root layout makes its reach clear.
  4. 4. Which statement about Tailwind in the App Router is true?

    Tailwind generates a normal stylesheet at build time and you use plain class names, so it needs no client JavaScript.

Summary

  • Import global CSS (resets, variables, base styles) once in the root layout.
  • CSS Modules rename classes per file, work with Server and Client Components, and need pure selectors.
  • Tailwind adds utility classes and generates only the CSS you use; Tailwind 4 is set up with @import "tailwindcss" and a PostCSS plugin.
  • Sass works with a sass install and .scss files; settings go in sassOptions.
  • Runtime CSS-in-JS needs Client Components and a registry; zero-runtime tools avoid both costs.
  • Do not rely on stylesheet order; use specificity.

Next: Bundle Size and Core Web Vitals