Sub topic 1
Styling for dark mode with the dark: variant
Prerequisites
This chapter assumes you have the following:
- Basic HTML and CSS, including how the cascade and specificity decide which rule wins.
- Familiarity with Tailwind utility classes and variants such as
hover:andmd:. - A project with Tailwind CSS already installed and producing a stylesheet.
- Enough JavaScript to read the DOM. Later chapters use
localStorage, but this one needs almost no scripting.
The chapter is about the dark: variant itself: what it generates, when it applies, and the mistakes that make it appear to do nothing. Later chapters in this tutorial cover the manual strategy, the toggle, persistence and flash prevention in detail. Here they are previewed only so you can see where the variant fits.
What the dark: variant does
A variant in Tailwind is a prefix that makes a utility apply only under a condition. hover:bg-gray-200 applies when the pointer is over the element. md:flex applies at the medium breakpoint and wider. dark:bg-gray-900 applies when dark mode is active.
Tailwind does not decide on its own what "dark mode is active" means. The variant is a condition, and the condition is configurable. By default, it is tied to the operating system or browser setting. You can change it to depend on a class or attribute in your markup.
Here is the smallest useful example:
<div class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<h1 class="text-2xl font-bold">Hello</h1>
<p class="text-gray-600 dark:text-gray-300">This card follows the active theme.</p>
</div>Read each class pair as "default value, then the dark override":
bg-whiteis the background in light mode.dark:bg-gray-900replaces it in dark mode.text-gray-900is the text color in light mode.dark:text-whitereplaces it in dark mode.text-gray-600on the paragraph becomesdark:text-gray-300.
Tailwind is mobile-first and light-first in the same way. Unprefixed utilities are your base styling, and dark: utilities are overrides layered on top. You never write a "light:" variant, because light is the default.
Why the override works
Tailwind generates the dark: utilities after the unprefixed ones in the stylesheet, and each one is wrapped in the condition for dark mode. With the default strategy, the generated CSS looks like this:
.bg-white {
background-color: #fff;
}
@media (prefers-color-scheme: dark) {
.dark\:bg-gray-900 {
background-color: #111827;
}
}Both rules have the same specificity, since each is a single class selector. The dark rule wins when it matches because it appears later in the file. That ordering is the reason you can pair bg-white and dark:bg-gray-900 on the same element without conflict. Only the conditional rule changes when the media query matches.
The exact color values depend on your Tailwind version and theme. Treat the output above as an illustration of the structure, not a literal copy.
Two strategies for deciding "dark"
There are two ways to define when dark: applies. Understanding the difference is the central idea of this chapter.
| Strategy | Condition | Who decides | Needs JavaScript |
|---|---|---|---|
| Media (default) | `@media (prefers-color-scheme: dark)` | The user's operating system or browser | No |
| Class or selector | A `.dark` class (or other selector) on an ancestor | Your page, through a toggle or stored preference | Yes |
Following the system preference
prefers-color-scheme is a CSS media feature. It reports whether the user has asked their device for a light or dark appearance. The browser exposes it, and your CSS can react to it without any script.
With the default strategy, you write dark: classes and nothing else. If the user's device is set to dark, the dark styles apply. If the user changes the system setting while your page is open, the page updates immediately, because the media query re-evaluates.
The strengths are simplicity and respect for the user's existing choice. The limit is that you cannot offer a toggle. The user's only way to change your site's theme is to change their whole system theme.
Taking control with a class or selector
Many sites let people pick a theme inside the page, independent of the system. For that you need dark: to depend on something you control. The common choice is a dark class on the <html> element. When the class is present, dark: utilities apply. When it is absent, they do not.
In this strategy the generated CSS keys off an ancestor instead of a media query. Conceptually:
.dark .dark\:bg-gray-900 {
background-color: #111827;
}Your JavaScript adds or removes the class. The CSS does the rest. Because the class is on an ancestor, every descendant can use dark: utilities.
Choosing between them
Use the media strategy when you want zero script and are happy to follow the system. Use the manual strategy when users need an in-page switch, or when your product has a brand preference that should override the system. Many production sites use the manual strategy with a three-way choice of light, dark and system, so they get both behaviors. That setup is built later in this tutorial.
Configuring the strategy
With no configuration, you get the media strategy in both Tailwind v3 and v4. Switching to a manual strategy is done differently in each version.
Tailwind v3
In v3, the darkMode option in tailwind.config.js controls the strategy. Setting it to 'selector' makes dark: apply when a .dark class is on an ancestor. In v3 releases before 3.4.1, the same behavior is spelled 'class'.
// tailwind.config.js (Tailwind v3.4.1 and later)
module.exports = {
darkMode: 'selector', // use 'class' in earlier v3 versions
content: ['./src/**/*.{html,js}'],
};Tailwind v4
Tailwind v4 has no darkMode option in a config file. Instead, you redefine the variant in your CSS with @custom-variant. The selector you provide is what dark: will match.
/* Tailwind v4 */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));The pattern &:where(.dark, .dark *) matches the element itself when it has the class, and any descendant of an element with the class. Using :where() keeps the added specificity at zero, so dark: utilities do not become harder to override than ordinary utilities.
You are not limited to a class. If your markup uses a data attribute, key the variant to that instead:
/* Tailwind v4, using a data attribute instead of a class */
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));This is useful when a design system or framework already sets data-theme on the root element.
The important point for this chapter is that the configuration changes only the condition. Your HTML, with its dark: classes, stays the same under every strategy.
Stacking dark: with other variants
Variants combine by chaining prefixes. Each prefix adds a condition, and all of them must be true for the utility to apply.
<button class="rounded bg-gray-100 px-3 py-1 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700">
Save
</button>This button has four relevant background rules:
bg-gray-100is the light resting state.hover:bg-gray-200is the light hover state.dark:bg-gray-800is the dark resting state.dark:hover:bg-gray-700is the dark hover state. It applies only when dark mode is active and the pointer is over the button.
A few points about stacking:
- You must write the dark hover state explicitly. Without
dark:hover:bg-gray-700, hovering in dark mode would fall back tohover:bg-gray-200, a light gray on a dark page. - Order of prefixes generally follows what reads naturally, such as
dark:md:flexormd:dark:flex. Both express "dark and medium breakpoint." Pick one order and use it consistently in a codebase. - Responsive, state and dark variants all stack, so
dark:md:hover:bg-gray-600is valid. Keep stacks short, because long ones are hard to read and maintain.
Specificity when variants collide
A common surprise is a state rule that beats your dark rule. Suppose a button has hover:bg-gray-200 dark:bg-gray-800. In dark mode, hovering the button applies hover:bg-gray-200, because the hover utility matches and nothing in dark mode overrides it. Both selectors are single-class-level rules in the same layer, so the later or more specific one wins, and the hover rule is the one that matches the hovered state. The fix is the stacked dark:hover: utility from the example above.
Common mistakes
These are the errors that account for most "dark mode does nothing" reports. Later chapters return to diagnosis in more depth.
- Strategy mismatch. You configured the class strategy but never add
.darkto any element. Nothing turns dark. The reverse also occurs: you rely on the default media strategy, then expect a class you add by hand to trigger it. It will not. - The class is on the wrong element. The
.darkclass must be on an ancestor of the styled element, or on the element itself in the v4 pattern shown above. Putting it on a sibling or child does nothing. - Wrong version syntax. Putting
darkMode: 'selector'in a v4 project has no effect, and writing@custom-variantin a v3 project is not recognized. Check which major version you installed. - Pre-3.4.1 value. In an older v3 release,
'selector'is not a valid value. Use'class'there. - Only half of a pair. You add
dark:bg-gray-900but forgetdark:text-white, leaving dark text on a dark background. Always set background and text together when you change one. - Dynamic class names. Tailwind finds classes by scanning your source files for complete strings. A class built by string concatenation, such as
'dark:bg-' + color, is never generated. Write the full class name somewhere in your source. - Content paths miss the file. In v3, a file not listed under
contentis not scanned, so itsdark:classes produce no CSS.
Designing the light and dark pair
Choosing dark values is a design decision, not a mechanical inversion. A few practical guidelines:
- Avoid pure black backgrounds with pure white text for long reading. The stark contrast can feel harsh. Dark grays such as
gray-900with softer text such asgray-100orgray-300are usually more comfortable. - Secondary text needs its own dark value. Swapping
text-gray-600fordark:text-gray-300keeps the hierarchy between headings and body copy. - Borders, shadows and dividers often need dark counterparts too. A light gray border can look glaring on a dark surface.
- Colored accents may need a lighter shade in dark mode so they stay legible against the darker background.
Contrast is covered fully in a later chapter. For now, treat each pair as something you should look at in both themes, not assume.
Putting it together
Here is a short checklist for adding dark support to a component:
- Decide your strategy: media by default, or a manual class or selector.
- If manual, configure it for your Tailwind version (
darkModein v3,@custom-variantin v4). - For each color utility on the component, add a
dark:counterpart, including text, background, border and accents. - Add
dark:hover:and other stacked variants wherever a light state style exists. - Test both themes. With the media strategy, switch your operating system setting or use your browser's rendering emulation for
prefers-color-scheme. With the manual strategy, add and remove the.darkclass on<html>in developer tools.
Exercise
A project uses Tailwind v4 with no extra configuration. A developer adds class="dark" to the <html> element, but elements with dark:bg-gray-900 stay light while the operating system is in light mode. Why does this happen, and what single line of CSS fixes it?
Show answer
In Tailwind v4 the default dark: variant uses the prefers-color-scheme media query, so a .dark class has no effect. Add @custom-variant dark (&:where(.dark, .dark *)); after @import "tailwindcss"; in your CSS so the variant keys off the .dark class.
Exercise
A button has the classes bg-gray-100 hover:bg-gray-200 dark:bg-gray-800. In dark mode, the button turns light gray when hovered. Which class do you add to keep it dark on hover, and why is it needed?
Show answer
Add dark:hover:bg-gray-700. Without it, the hover:bg-gray-200 utility still matches on hover in dark mode, since nothing dark-specific overrides the hover state. The stacked variant applies only when both dark mode and hover are active.
Exercise
In a Tailwind v3.2 project you set darkMode: 'selector' and the dark: classes still do nothing when .dark is on <html>. What is the likely cause and fix?
Show answer
The 'selector' value was added in Tailwind v3.4.1. In earlier v3 releases the option must be 'class'. Change the value to 'class' or upgrade Tailwind to 3.4.1 or later.