Skip to content
Visual explainer 1h 30m to learn 3 steps

Theming & dark mode

Support light and dark themes with CSS variables.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 29 of 36

In short

Theming stores colors in CSS variables and swaps their values per theme. Respect the user's system preference by default, and let them override it with a toggle that is remembered.

Explained simply

Many people set their phone or laptop to dark mode, especially at night. A good website notices this and switches to dark colors by itself. It should also let people pick light or dark by hand, and remember that choice next time.

The trick is to never write a color directly in a component. Instead, components use named colors like background and text. Those names are CSS variables. In light mode, background means white; in dark mode, the same name means almost black. Swap the values and the whole app changes at once.

The browser tells you the system setting through a media query called prefers-color-scheme. Your saved choice, if any, wins over it. That choice is usually stored in localStorage or a cookie.

The tricky part is timing. If your page first paints in light mode and then a script switches it to dark, users see an ugly white flash. The fix is a tiny script that sets the theme before the first paint.

Press Play on a diagram to walk through it one step at a time.

FlowChoosing the active theme
  1. Step 1
    Saved choice?

    Read the user's stored theme, if any

  2. Step 2
    System preference

    Otherwise use prefers-color-scheme

  3. Step 3
    Set data-theme

    Put the theme on the html element

  4. Step 4
    Variables switch

    CSS variables change, every component updates

LayersWhich theme wins
  1. 1
    User's saved choice

    light or dark in localStorage or a cookie

  2. 2
    System preference

    prefers-color-scheme from the OS

  3. 3
    Site default

    Usually light, used when nothing else is known

In depth

Designing dark colors, not just inverting

Dark mode is not light mode with the colors flipped. Pure black backgrounds with pure white text cause glare and halos for many readers, so most designs use a dark grey or navy background and slightly softened text. Elevated surfaces like cards and menus get a little lighter than the page, because shadows barely show on dark backgrounds.

Saturated brand colors often look too bright on dark, so you may need a lighter, less intense version. Check contrast for both themes: at least 4.5:1 for normal text. Images and illustrations may need their own versions, and you can use the picture element with a media attribute to serve a dark image.

  • Use dark grey (for example #0b0f19) rather than #000
  • Raise surfaces with lighter fills instead of shadows
  • Re-check contrast in both themes

Telling the browser about your theme

The CSS property color-scheme tells the browser which themes your page supports. Set color-scheme: light dark on :root and native parts like form controls, scrollbars and the default canvas follow the active theme. When the user forces a theme, set color-scheme: dark on that theme's selector too, or native inputs stay light.

Modern CSS also has a light-dark() function: color: light-dark(#111, #eee) picks the first value in light scheme and the second in dark, based on color-scheme. It is supported in all major browsers since 2024. In JavaScript, window.matchMedia("(prefers-color-scheme: dark)") reads the setting, and its change event fires when the user flips their system theme.

  • :root { color-scheme: light dark; }
  • [data-theme="dark"] { color-scheme: dark; }
  • light-dark(a, b) needs color-scheme to be set

Avoiding the flash on first paint

In a server-rendered app, the server does not know what is in the browser's localStorage. So the HTML arrives without the user's choice. If React applies the theme after hydration, the page has already painted in the wrong colors.

There are two good fixes. One: a small inline script in the head reads localStorage and sets data-theme on the html element before the body paints. Because the server HTML and the browser DOM now differ on that one attribute, add suppressHydrationWarning to the html tag. The next-themes library does exactly this for you. Two: store the choice in a cookie, read it on the server with cookies(), and render the right data-theme straight into the HTML. The cookie way makes the route dynamic, so it costs static caching.

SequenceLoading a page with a saved dark theme
Server
Browser
Inline head script
React
  1. 1HTML with no theme attribute
    Server to Browser: HTML with no theme attribute
  2. 2Runs before body paints
    Browser to Inline head script: Runs before body paints
  3. 3Reads localStorage, sets data-theme=dark
    Inline head script to Browser: Reads localStorage, sets data-theme=dark
  4. 4Paints dark, then loads JS
    Browser to React: Paints dark, then loads JS
  5. 5Hydrates; toggle shows Dark
    React to Browser: Hydrates; toggle shows Dark

Wiring Tailwind's dark variant to your toggle

By default, Tailwind's dark: variant follows prefers-color-scheme, so dark:bg-gray-900 works with no setup. Once you add a manual toggle, you need dark: to follow your attribute instead. In Tailwind v4, add one line to your CSS: @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)). Now dark: applies inside any element with data-theme="dark".

A cleaner approach for big apps is to rarely use dark: at all. Define semantic colors such as --color-bg and --color-fg in @theme, then redefine those variables under [data-theme=dark]. Components just use bg-bg and text-fg and never think about themes. Save dark: for the odd exception, like a logo that needs a different shade.

  • @custom-variant dark (&:where(.dark, .dark *)); for a class toggle
  • Prefer semantic variables over many dark: classes
  • A three-way toggle: light, dark, system

Learn it in 3 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Define theme colors as CSS variables~30m
  2. 2
    Respect prefers-color-scheme~30m
  3. 3
    Add a persisted theme toggle~30m

Key points

  • Define colors once as CSS variables and redefine them for dark mode.
  • prefers-color-scheme reads the operating system's light or dark setting.
  • Apply the saved theme before first paint to avoid a flash of the wrong theme.
  • Check contrast in both themes, not just light.

Key terms

Tap a card to flip it. 0/4 known

Examples

css
:root { --bg: #ffffff; --text: #111827; }

@media (prefers-color-scheme: dark) {
  :root:not([data-theme='light']) { --bg: #0b0f19; --text: #e5e7eb; }
}

:root[data-theme='dark'] { --bg: #0b0f19; --text: #e5e7eb; }

body {
  background: var(--bg);
  color: var(--text);
}

System preference by default, with a manual override.

A three-way theme toggle

You want Light, Dark and System options. Step 1: store the choice as "light", "dark" or "system" in localStorage. Step 2: to apply it, if the choice is system, read matchMedia; otherwise use the choice. Step 3: set data-theme on document.documentElement. Step 4: while on system, listen for the media query change event so the page follows the OS live. Wrap localStorage in try and catch, because it can throw in private modes.

ts
type Choice = "light" | "dark" | "system";
const mq = window.matchMedia("(prefers-color-scheme: dark)");

export function applyTheme(choice: Choice) {
  const dark = choice === "dark" || (choice === "system" && mq.matches);
  document.documentElement.dataset.theme = dark ? "dark" : "light";
  try { localStorage.setItem("theme", choice); } catch {}
}

mq.addEventListener("change", () => {
  let saved: string | null = null;
  try { saved = localStorage.getItem("theme"); } catch {}
  if (!saved || saved === "system") applyTheme("system");
});

No flash in the Next.js root layout

Step 1: in app/layout.tsx, add a tiny script string that runs before paint and sets data-theme. Step 2: render it with dangerouslySetInnerHTML inside head, so it runs synchronously. Step 3: add suppressHydrationWarning to the html tag, because the attribute differs from the server HTML. Step 4: reload with dark saved and confirm there is no white flash, even with network throttling on.

tsx
const themeScript = `try{var t=localStorage.getItem('theme');
var d=t==='dark'||((!t||t==='system')&&matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme=d?'dark':'light'}catch(e){}`;

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <script dangerouslySetInnerHTML={{ __html: themeScript }} />
      </head>
      <body>{children}</body>
    </html>
  );
}

Quick reference

  • @media (prefers-color-scheme: dark) { ... } follows the OS setting
  • :root { color-scheme: light dark; } makes form controls and scrollbars match
  • color: light-dark(#111, #eee) picks a value by the active color scheme
  • matchMedia("(prefers-color-scheme: dark)").matches reads the setting in JS
  • Set the theme in an inline head script to avoid a flash of the wrong theme
  • Add suppressHydrationWarning on html when a script changes its attributes
  • Tailwind v4: @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));

Common mistakes

  • Hard-coding colors in components, so they ignore the theme.
  • Reading localStorage after render and flashing the wrong theme.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your dark theme works, but native select boxes and scrollbars stay light. What is missing?

Question 2

2Why does reading localStorage in a useEffect cause a white flash?

Question 3

3What does Tailwind's dark: variant follow if you change nothing?

Question 4

4A user chose Dark on your site but their OS is in light mode. What should the site show?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Define --bg and --fg for light mode, redefine them for prefers-color-scheme dark, and apply them to body.

  2. Exercise 2medium

    Extend the easy solution so a data-theme attribute on html can force light or dark, whatever the system says.

  3. Exercise 3hard

    Build a ThemeToggle client component that cycles light, dark, system, shows the current choice and keeps it after reload without a flash.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use next-themes or write my own?
next-themes is small, handles the inline script, system changes and syncing across tabs, so it is a good default. Writing your own is fine for learning and takes about 20 lines.
Is dark mode better for the eyes or the battery?
It can save battery on OLED screens, where black pixels are off. For reading comfort it depends on the person and the room, which is why letting users choose matters.
Should I store the theme in localStorage or a cookie?
localStorage is simplest and keeps pages static. A cookie lets the server render the right theme directly, but reading cookies makes those routes dynamic in Next.js.
ShareXLinkedInWhatsApp