Sub topic 10
Dark mode with the dark variant
This chapter assumes you know basic HTML and CSS, can run npm commands, and have read the earlier chapters on colors, state variants, and how Tailwind generates CSS. You should know that a variant is a prefix such as hover: that limits a utility to a condition.
What the dark variant does
The dark: prefix applies a utility only when dark mode is active. Without the prefix, the utility always applies. With it, the utility applies only under the dark condition.
<div class="bg-white text-slate-900 dark:bg-slate-900 dark:text-white">
Adapts to the dark color scheme.
</div>In light mode this element has a white background and near-black text. In dark mode, the dark: utilities take over, giving a near-black background and white text.
You write both themes in the same element. You do not need a second stylesheet or a separate set of class names.
How "dark mode is active" is decided
By default, Tailwind ties dark: to the operating system or browser preference. It does this with the CSS media query prefers-color-scheme: dark. The generated CSS looks roughly like this:
@media (prefers-color-scheme: dark) {
.dark\:bg-slate-900 {
background-color: var(--color-slate-900);
}
}If the user's system is set to dark, the dark utilities apply. If it is set to light, they do not. Your page needs no JavaScript for this.
This default has one limit. The user cannot override their system setting from inside your page. If you want a theme toggle, you must change the strategy, as described below.
Writing dark styles: the pairing pattern
A reliable habit is to treat each color utility as a pair: the light value with no prefix, and the dark value with dark:.
| Purpose | Light | Dark |
|---|---|---|
| Page background | `bg-white` | `dark:bg-slate-900` |
| Primary text | `text-slate-900` | `dark:text-white` |
| Secondary text | `text-slate-600` | `dark:text-slate-400` |
| Border | `border-slate-200` | `dark:border-slate-700` |
| Card surface | `bg-slate-50` | `dark:bg-slate-800` |
Notice that the dark values are not simple inversions. Pure white text on pure black can look harsh. Picking slate 900 for the background and slate 400 for muted text gives softer contrast. Check that text still meets contrast guidelines in both themes.
Here is a card that uses the pairing pattern:
<div class="max-w-sm rounded-xl border border-slate-200 bg-white p-6 shadow-md dark:border-slate-700 dark:bg-slate-800">
<h2 class="text-xl font-semibold text-slate-900 dark:text-white">Card title</h2>
<p class="mt-2 text-slate-600 dark:text-slate-400">Some supporting text for the card.</p>
<button class="mt-4 rounded-lg bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-400">
Read more
</button>
</div>Only properties that need to change get a dark: partner. The rounded-xl, p-6, and shadow-md utilities stay as they are.
Stacking dark with other variants
Variants combine. Put them in a chain, and the element must satisfy all of them for the utility to apply.
<button class="bg-indigo-600 hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-400">
Save
</button>Here dark:hover:bg-indigo-400 applies only when dark mode is active and the pointer is over the button. You can also add breakpoints, as in md:dark:bg-slate-800.
In Tailwind v4, stacked variants are applied from left to right. Most of the time the order does not change the result, but it can matter for variants that wrap selectors, such as group-hover:. If a stacked variant does not behave as you expect, try reordering it and inspect the generated CSS.
Switching to a manual toggle
To let users choose a theme in your page, you tell Tailwind that dark: should depend on a class or attribute on an ancestor element, usually <html>, instead of the media query. In Tailwind v4, you do this with the @custom-variant directive in your CSS.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));This redefines dark: so that it matches an element that has the dark class, or is inside one that does. The :where() wrapper keeps the added selector's specificity at zero, so it does not make dark utilities harder to override.
With that in place, the dark utilities apply only when <html class="dark"> is present:
<html class="dark">
<body class="bg-white dark:bg-slate-900">
<!-- dark styles are active here -->
</body>
</html>You can use a data attribute instead of a class:
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));Then you set data-theme="dark" on <html>.
Strategy comparison
| Strategy | How dark mode is triggered | User can override? | Needs JavaScript? |
|---|---|---|---|
| Default (media query) | System or browser setting | No | No |
| Class or attribute selector | `dark` class or data attribute on an ancestor | Yes | Yes, to set the class |
| Hybrid (system default, with override) | Class or attribute, set from the system preference at first load | Yes | Yes |
Choose the default when you want the simplest setup and are happy to follow the system. Choose a selector strategy when the product needs a visible theme switch.
Building a toggle with three choices
Most toggles offer three options: light, dark, and system. The usual approach stores the choice in localStorage and sets the dark class on <html>.
Put this script in the <head>, before the page paints:
<script>
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches)
);
</script>The logic reads as follows. If the user saved dark, add the class. If the user saved nothing, follow the system preference. If the user saved light, the condition is false and the class is removed.
Here are functions that a toggle control can call:
function setLight() {
localStorage.theme = "light";
document.documentElement.classList.remove("dark");
}
function setDark() {
localStorage.theme = "dark";
document.documentElement.classList.add("dark");
}
function setSystem() {
localStorage.removeItem("theme");
document.documentElement.classList.toggle(
"dark",
window.matchMedia("(prefers-color-scheme: dark)").matches
);
}Using design tokens to reduce repetition
Writing a dark: partner on every element gets noisy. One way to cut it down is to define semantic tokens as CSS variables and change the variable values in dark mode. The utilities then stay the same in both themes.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@theme inline {
--color-surface: var(--surface);
--color-content: var(--content);
}
:root {
--surface: #ffffff;
--content: #0f172a;
}
.dark {
--surface: #0f172a;
--content: #ffffff;
}Now bg-surface and text-content exist as utilities. They change with the theme without any dark: prefix:
<main class="bg-surface text-content">
Same classes, different values per theme.
</main>The inline option tells Tailwind to put the variable reference directly in the generated utility. Without it, Tailwind may resolve the value at the wrong place in the cascade when variables refer to other variables.
Which approach fits? Use explicit dark: pairs when only a few elements differ or the dark design diverges from the light one. Use semantic tokens when many elements share the same roles, such as surface and text, and you want a theme change to touch one place.
Common errors
- Dark styles never apply. You switched to a class strategy but forgot to add the
darkclass to an ancestor. Check that<html>has it. - Toggle has no effect. You kept the default media query strategy and are changing a class. The class is ignored until you define the custom variant.
- Old v3 configuration. In Tailwind v3, you set
darkMode: 'class'intailwind.config.js. In v4, that option is replaced by@custom-variantin CSS. Check which version you use before copying snippets. - Missing light value. A
dark:bg-slate-900with no basebg-*leaves the light theme with whatever the element inherited, which is often transparent. - Dynamic class names. Building
dark:bg-${color}-900in JavaScript fails for the same reason as any dynamic class. Tailwind must see the full class name in your source. - Forgotten third-party content. Images, borders, and shadows may look wrong on dark surfaces. A dark shadow on a dark background is invisible, so consider a border or lighter surface for elevation.
- Form controls. Native controls such as scrollbars and checkboxes follow the browser's color scheme. Add
color-scheme: darkwith thescheme-darkutility, or apply it from your.darkrule, so they match.
<html class="dark scheme-dark">Testing dark mode
You do not need to change your operating system to test the default strategy. Browser developer tools can emulate the preference. In Chrome and Edge, open the Rendering panel and set "Emulate CSS media feature prefers-color-scheme". Firefox offers a similar button in the Inspector. For a class strategy, toggle the class on <html> in the Elements panel.
Test both themes for text contrast, focus rings, hover states, and images with transparent backgrounds.
Exercise
A page uses Tailwind v4 with the default dark mode setup. You add a button that adds the class dark to <html>, but the page does not change, although dark:bg-slate-900 appears on the body. What is wrong, and what one line of CSS fixes it?
Show answer
By default, dark: follows the prefers-color-scheme media query, so the class is ignored. Add @custom-variant dark (&:where(.dark, .dark *)); after @import "tailwindcss"; so that dark: matches elements inside an ancestor with the dark class.
Exercise
You define --color-surface: var(--surface); inside @theme inline and set --surface to white in :root and to slate 900 in .dark. Do you need to write dark:bg-surface on an element? Explain.
Show answer
No. bg-surface reads the --surface variable, and the variable's value changes when the dark class is present. The utility itself stays the same, so a single bg-surface works in both themes.
Exercise
Why should the theme script that reads localStorage run in the <head> instead of at the end of <body>?
Show answer
A script in the <head> sets the dark class before the browser paints the page. A script at the end of the body runs after the first paint, so dark-mode users briefly see the light theme before it switches.