Sub topic 7
Adding dark mode
Dark mode in Tailwind is a variant, like hover: or sm:. You write dark:bg-gray-900 next to bg-white, and the dark class applies only when dark mode is active. This chapter covers how Tailwind decides when dark mode is active, how to switch it from React, and the mistakes that most often break it.
This chapter assumes you have a Vite and React project with Tailwind v4 set up, and that you know how state variants such as hover: and breakpoint variants such as sm: combine with utilities. You should also be comfortable with useState and useEffect.
How the dark: variant works by default
In Tailwind v4, the dark: variant uses the CSS media query prefers-color-scheme: dark. The browser sets this from the operating system or browser setting. You don't write any configuration for it.
export function Panel() {
return (
<div className="rounded-lg border border-gray-200 bg-white p-6 text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100">
<h2 className="text-lg font-semibold">Weekly report</h2>
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
Updated every Monday.
</p>
</div>
)
}Each element lists its light styles first and its dark overrides after. The dark: classes win only when the media query matches. Otherwise they have no effect.
This default is enough if you want the app to follow the system and give users no control. Most apps eventually want a toggle, which needs a different strategy.
Choosing a strategy
There are three common approaches. They differ in who decides the theme.
| Strategy | Who decides | Needs a variant override | Typical use |
|---|---|---|---|
| System only | The operating system | No | Simple sites, internal tools |
| Manual toggle | The user, through your UI | Yes | Apps with a theme switch |
| System default plus override | The system until the user chooses | Yes | Most production apps |
The second and third strategies rely on a class on an ancestor element, usually <html>. The class is your own signal, and your React code controls it.
Switching to class-based dark mode
Tailwind v4 has no darkMode setting in a JavaScript config file. Instead you redefine the dark variant in CSS with @custom-variant.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));The selector means: apply the dark styles to an element that has the dark class, or to any element inside one. The :where() wrapper gives the selector zero specificity. That keeps dark: utilities from becoming harder to override than ordinary utilities.
After this change the media query is no longer used. If a user's system is set to dark but <html> has no dark class, the page stays light. Your code now owns the decision.
Toggling the class from React
The class belongs on document.documentElement, which is the <html> element. That element sits outside your React tree, so you change it in an effect.
A hook can keep the theme in state, persist it, and apply it.
import { useEffect, useState } from 'react'
type Theme = 'light' | 'dark'
const STORAGE_KEY = 'theme'
function getInitialTheme(): Theme {
const stored = localStorage.getItem(STORAGE_KEY)
if (stored === 'light' || stored === 'dark') return stored
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
export function useTheme() {
const [theme, setTheme] = useState<Theme>(getInitialTheme)
useEffect(() => {
document.documentElement.classList.toggle('dark', theme === 'dark')
localStorage.setItem(STORAGE_KEY, theme)
}, [theme])
const toggle = () => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))
return { theme, toggle }
}The initial value comes from storage first. If the user has never chosen, it falls back to the system preference. This gives you the "system default plus override" strategy.
A button then uses the hook.
import { useTheme } from './useTheme'
export function ThemeToggle() {
const { theme, toggle } = useTheme()
return (
<button
onClick={toggle}
aria-pressed={theme === 'dark'}
className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-900 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-100 dark:hover:bg-gray-800"
>
{theme === 'dark' ? 'Switch to light' : 'Switch to dark'}
</button>
)
}Note the dark:hover:bg-gray-800 class. Variants stack, and they are applied from right to left in the class name. This one means "when dark mode is active and the pointer is over the element". Stacking works with breakpoints too, for example dark:md:bg-gray-800.
Avoiding the flash of the wrong theme
The hook above runs after React mounts. A user who chose dark will first see the light page, then a flash as the class is added. In a Vite single-page app, the HTML file loads before your JavaScript bundle, so the gap is visible.
The fix is a small inline script in index.html that sets the class before the first paint.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My app</title>
<script>
(function () {
var stored = localStorage.getItem('theme')
var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
if (stored === 'dark' || (!stored && prefersDark)) {
document.documentElement.classList.add('dark')
}
})()
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>The script is a plain script, not a module, so it runs immediately and blocks rendering for a moment. It is short on purpose. Keep the storage key and the logic identical to the hook, or the two will disagree.
You can also tell the browser which color schemes your page supports. This makes built-in elements such as scrollbars and form controls match the theme.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@layer base {
html {
color-scheme: light;
}
html.dark {
color-scheme: dark;
}
}How the pieces fit together
The flow below shows who sets the class and when.
Designing colors that work in both themes
Writing dark: next to every color class gets repetitive. Two approaches reduce it.
The first is to pair colors from the same scale. A common pattern is bg-white dark:bg-gray-900 for surfaces, text-gray-900 dark:text-gray-100 for body text, and text-gray-600 dark:text-gray-400 for secondary text. Using one pair consistently across components keeps the look coherent.
The second is to define semantic tokens in the theme and change their values with the dark class. This is where the theme chapter's @theme block helps. Tokens defined there become CSS variables, so you can override the variables under .dark.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--color-surface: #ffffff;
--color-content: #111827;
}
.dark {
--color-surface: #111827;
--color-content: #f3f4f6;
}Now bg-surface text-content works in both themes with no dark: prefix. The trade-off is that the mapping lives in CSS instead of next to each element. Use tokens for colors that appear everywhere, and keep dark: for one-off differences.
Common errors
- The toggle does nothing. The
@custom-variantline is missing, so Tailwind still uses the media query. Add the line and restart the dev server if needed. - Dark classes never appear in the build. Tailwind finds classes by scanning for complete strings.
dark:${bg}built from fragments is not detected. Use full class names, as covered in the class detection chapter. - Only some elements change. An element has a hard-coded color with no
dark:pair, such astext-gray-900on a dark surface. Check each color class for a counterpart. - A flash of light theme on reload. The class is set only after React mounts. Add the inline script.
- Server-rendered pages mismatch. If you later move to a framework that renders on the server, reading
localStorageduring render produces different HTML on the server and the client. Read it in an effect or in an inline script instead. - Stored value is invalid. A hand-edited or old value in storage can break assumptions. The
getInitialThemefunction above validates the value before using it.
Summary of decisions
- Use the default media-query variant when the app should follow the system and nothing else.
- Use
@custom-variant darkwith a.darkclass when users need a switch. - Resolve the stored choice before first paint with an inline script.
- Prefer semantic color tokens for colors used in many places.
Exercise
Your app uses @custom-variant dark (&:where(.dark, .dark *));. A user whose operating system is set to dark mode opens the app for the first time, and the page shows in light theme. What is the cause, and what is the smallest change to the React code that makes first-time visits follow the system?
Show answer
With the custom variant, dark: styles apply only when an ancestor has the dark class, so the system preference is ignored. Nothing adds the class on a first visit. The fix is to read window.matchMedia('(prefers-color-scheme: dark)').matches when no stored choice exists, and use it as the initial theme, as getInitialTheme does. The effect then adds the dark class to document.documentElement.
Exercise
Why does the inline script in index.html need to be a plain script rather than part of the React bundle, and what happens if its storage key differs from the one in useTheme?
Show answer
A plain inline script runs while the HTML is parsed, before the bundle loads and before the first paint, so the correct class is on <html> from the start. Code in the bundle runs later and causes a flash of the wrong theme. If the keys differ, the script and the hook read different values. The page may load in one theme and then switch to another once React mounts.