How do you use CSS variables in Next.js?

Define custom properties in globals.css (for example on :root and a .dark class), use them with var(--name) in any CSS, CSS Module or Tailwind theme, and set dynamic values from React with the style prop. next/font can also expose fonts as CSS variables.

Where to use them

  • Design tokens: colors, spacing, radii, shadows, defined once in :root.
  • Theming: redefine tokens under .dark or [data-theme="brand"].
  • Tailwind v4: map tokens into @theme (or @theme inline) so utilities like bg-background use them.
  • Fonts: Inter({ variable: "--font-inter" }) adds a class that defines --font-inter.
  • Dynamic values from data: style={{ "--progress": "40%" }} in a Server Component, with CSS doing the rest, without client JavaScript.

Why they suit the App Router

They work in Server Components because they are plain CSS. Changing a theme only requires changing a class or attribute on <html>, and no component re-renders.

TypeScript

style objects do not know custom properties by default. Cast: { "--x": value } as React.CSSProperties, or extend CSSProperties with a module declaration.

Tips

  • Inherit naturally: set a variable on a parent and children use it.
  • Fallbacks: var(--accent, #4f46e5).
  • Use @property to type variables and animate them.

Code example

tsx
1/* app/globals.css */
2// :root { --radius: 12px; --brand: #4f46e5; --surface: #fff; }
3// [data-theme="dark"] { --surface: #0f172a; }
4// .progress { height: 8px; border-radius: var(--radius); background: #e2e8f0; }
5// .progress > span { display: block; height: 100%; width: var(--value, 0%); background: var(--brand); }
6
7// app/goals/page.tsx - Server Component, no client JS needed
8import { getGoals } from "@/lib/goals";
9
10export default async function Goals() {
11 const goals = await getGoals();
12 return (
13 <ul>
14 {goals.map((g) => (
15 <li key={g.id}>
16 {g.name}
17 <div className="progress">
18 <span style={{ "--value": `${g.percent}%` } as React.CSSProperties} />
19 </div>
20 </li>
21 ))}
22 </ul>
23 );
24}

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.

Open in study app