Skip to content

Blog

Tailwind dark mode in v4: class toggle without a flash

Frank Spin7 min read

Dark mode in Tailwind CSS v4 works out of the box: dark:bg-black applies when the operating system is set to dark. For a toggle on your site you add one line of CSS, @custom-variant dark (&:where(.dark, .dark *));, and a few lines of JavaScript that set the class before the page paints. This guide has both, the token approach shadcn/ui uses so you barely need dark: at all, and the details that make it feel finished: no white flash, native scrollbars and a light/dark/system switch.

Every CSS snippet was compiled with Tailwind 4.3.3; the output shown is what it produced.

Dark mode from the system setting#

Without any configuration, the dark: variant follows the reader's operating system:

<div class="bg-white text-zinc-900 dark:bg-zinc-950 dark:text-zinc-100">…</div>

compiles to

@media (prefers-color-scheme: dark) {
  .dark\:bg-zinc-950 { background-color: var(--color-zinc-950); }
}

If your site doesn't need a toggle, stop here. Following the system setting is what most readers expect, and there's no JavaScript and no flash.

A class-based toggle#

To let readers choose, tell Tailwind that dark: means "inside an element with the class dark" instead of the media query. In v4 that's a custom variant in your CSS; there's no darkMode: 'class' config any more:

@import "tailwindcss";

@custom-variant dark (&:where(.dark, .dark *));

Now dark:bg-zinc-950 compiles to .dark\:bg-zinc-950:where(.dark, .dark *), and you switch themes by adding or removing class="dark" on <html>. The :where() keeps the selector's specificity at zero, so dark: classes don't win fights they shouldn't.

Prefer a data attribute? Same idea:

@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));

Tokens instead of dark: on every element#

Writing bg-white dark:bg-zinc-950 on every element gets old fast, and it's how dark mode bugs happen: one component forgets the dark: half. The alternative, and what shadcn/ui does, is to name colours by their role and switch the values once:

@import "tailwindcss";

@custom-variant dark (&:where(.dark, .dark *));

:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.145 0 0);
  --muted-foreground: oklch(0.556 0 0);
  --border: oklch(0.922 0 0);
}

.dark {
  --background: oklch(0.145 0 0);
  --foreground: oklch(0.985 0 0);
  --muted-foreground: oklch(0.708 0 0);
  --border: oklch(1 0 0 / 10%);
}

@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --color-muted-foreground: var(--muted-foreground);
  --color-border: var(--border);
}

The markup then has no dark: at all:

<div class="border bg-background text-foreground">
  <p class="text-muted-foreground">Works in both themes.</p>
</div>

@theme inline is needed because the values are variables that change under .dark; without inline, Tailwind would resolve them once on :root. Keep dark: for the exceptions: a different image, a shadow that should disappear, an illustration that needs inverting.

You don't have to pick these values by hand. Each of the 37 shadcn/ui presets on themes.dev comes with a light and a dark set of all the tokens, and the shadcn theme generator makes a matching pair from one brand colour, contrast-checked in both modes.

The toggle without a flash#

The classic dark mode bug: a reader who chose dark gets a white page for a split second on every load, because the script that adds .dark runs after the first paint. The fix is a tiny blocking script in the <head>, before your CSS:

<script>
  (() => {
    const stored = localStorage.getItem("theme") // "light", "dark" or null for system
    const dark = stored ? stored === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
    document.documentElement.classList.toggle("dark", dark)
  })()
</script>

It has to be inline and not type="module" or defer, because those run after the page is parsed. In Astro, write it as <script is:inline> so Astro doesn't bundle and defer it. In Next.js, the next-themes package injects the same kind of script for you and handles the hydration warning on <html>.

A light, dark and system switch#

A two-state toggle forgets the system setting forever after one click. Three states, with "system" as the default, respect both choices:

<div role="group" aria-label="Theme">
  <button type="button" data-theme-choice="light">Light</button>
  <button type="button" data-theme-choice="dark">Dark</button>
  <button type="button" data-theme-choice="system">System</button>
</div>

<script>
  const media = matchMedia("(prefers-color-scheme: dark)")

  function apply() {
    const stored = localStorage.getItem("theme")
    const dark = stored ? stored === "dark" : media.matches
    document.documentElement.classList.toggle("dark", dark)
    for (const button of document.querySelectorAll("[data-theme-choice]")) {
      button.setAttribute("aria-pressed", String(button.dataset.themeChoice === (stored ?? "system")))
    }
  }

  for (const button of document.querySelectorAll("[data-theme-choice]")) {
    button.addEventListener("click", () => {
      const choice = button.dataset.themeChoice
      choice === "system" ? localStorage.removeItem("theme") : localStorage.setItem("theme", choice)
      apply()
    })
  }

  // Readers on "system" follow the OS when it switches at sunset.
  media.addEventListener("change", apply)
  apply()
</script>

aria-pressed tells screen readers which option is active, and you can style it with aria-pressed:bg-accent instead of a separate class. Wrap the localStorage calls in try/catch if you support browsers with storage blocked; reading it throws there.

Scrollbars, form controls and the browser UI#

Tailwind's dark: classes only change what you style. Scrollbars, <select> menus, date pickers and the autofill background are drawn by the browser, and they stay light unless you tell it otherwise with color-scheme. v4 has utilities for it:

<html class="scheme-light dark:scheme-dark">

scheme-dark sets color-scheme: dark; for a site that only follows the system, scheme-light-dark on <html> does it in one class. Add <meta name="theme-color"> with a media attribute for each mode if you want the mobile browser bar to match too.

FAQ#

How do I enable dark mode in Tailwind v4?

It's on by default and follows the system setting through prefers-color-scheme. For a manual toggle, add @custom-variant dark (&:where(.dark, .dark *)); to your CSS and put the dark class on <html>.

What replaced darkMode: 'class' in Tailwind v4?

The @custom-variant rule in CSS. @custom-variant dark (&:where(.dark, .dark *)); is the v4 equivalent of darkMode: 'class', and with [data-theme="dark"] in place of .dark it replaces darkMode: ['selector', '[data-theme="dark"]'].

Why does my page flash white before switching to dark?

The dark class is added after the first paint. Move the script that reads the saved choice into the <head> as a plain inline script (not a module, not deferred), before the stylesheet.

Should I use dark: classes or CSS variables?

Variables for colours that every element uses (background, text, borders), set once for :root and .dark; dark: for one-off exceptions. That's the shadcn/ui approach, and it means a component can't forget its dark half.

Built on Tailwind CSS v4

1401 finished blocks on shadcn/ui, React and Astro

UI Pro, from €199

Build it with

Preview

Open the page
In UI Pro: get it, €199 once

With every block and theme. 400+ buyers since 2020. Plans

UI Pro

Build your next site from finished blocks

Every block, page template and website theme from €199, paid once, with every update and everything we add later. Not ready? The free blocks are open to everyone.

blocks
1401
page templates
55
website themes
29
The Case study page template from UI Pro, built from its blocks.

This page is built from UI Pro blocks: Zandloper (article-14), Rooilijn (call-to-action-07).