Sub topic 9
Reducing repetition with CSS variables
This chapter assumes you can already style elements with dark:, you have chosen a strategy (system preference or a .dark class), and you know basic CSS custom properties. If your dark: classes still do nothing, finish the configuration chapter first. This chapter is about what happens after it works: your markup fills up with paired classes, and you want to cut that down.
The problem: paired classes everywhere
The dark: variant is explicit. For each color you want to change, you write a light class and a dark class:
<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>That is fine for a single card. In a real application, the same pairing, white surface with dark text and the inverse, shows up in dozens of components. This causes three problems:
- Repetition. Every component restates the same two color decisions.
- Drift. One developer writes
dark:bg-gray-900, another writesdark:bg-slate-900, and the dark theme slowly becomes inconsistent. - Expensive redesigns. Changing the dark background means searching every template for the class.
CSS variables (also called custom properties) move the light/dark decision out of the markup and into one place in your stylesheet.
The core idea: one name, two values
A CSS variable is a named value you declare once and read with var(--name). Its value depends on where it is declared, and descendants inherit it. That inheritance is what makes theming work. You declare the same names twice, once for light and once for dark, and components read the names without knowing which theme is active.
:root {
--surface: #ffffff;
--text: #111827;
color-scheme: light;
}
.dark {
--surface: #111827;
--text: #f9fafb;
color-scheme: dark;
}Here :root is the <html> element. It holds the light values by default. When the dark class is on <html>, the .dark rule has the same or higher specificity for those names and appears later, so its values win. Every element beneath <html> inherits the new values automatically.
The color-scheme lines are a separate concern: they tell the browser to draw native controls and scrollbars in the matching theme. A later chapter covers them in detail. Keeping them next to the variables means each theme block describes the whole theme in one place.
Using the variables in Tailwind classes
Tailwind lets you put any CSS value in square brackets, which is called an arbitrary value. Combined with var(), a single class works in both themes:
<div class="bg-[var(--surface)] text-[var(--text)]">
<h1 class="text-2xl font-bold">Hello</h1>
<p class="opacity-70">No dark: classes here.</p>
</div>The markup contains no dark: at all. When the theme changes, only the variable values change, and the browser repaints.
Note the trade-off. You gave up the visible, per-element dark: pairing in exchange for a central definition. Someone reading the HTML can no longer see what the dark color is without opening the stylesheet.
Naming variables by role, not by color
The names --surface and --text describe what a color is for. Avoid names like --white or --gray-900, because in the dark theme --white would hold a dark color, which is confusing.
A small, role-based set covers most interfaces:
| Variable | Role | Light value | Dark value |
|---|---|---|---|
| `--surface` | Page or card background | `#ffffff` | `#111827` |
| `--surface-raised` | Elements above the surface, such as menus | `#f3f4f6` | `#1f2937` |
| `--text` | Primary text | `#111827` | `#f9fafb` |
| `--text-muted` | Secondary text | `#4b5563` | `#d1d5db` |
| `--border` | Dividers and outlines | `#e5e7eb` | `#374151` |
Keep the set small. Every variable you add is another name to define in both themes and to keep in sync.
Doing it the Tailwind v4 way: `@theme`
In Tailwind v4 you can register your variables as theme tokens, which gives you real utility classes like bg-surface instead of bg-[var(--surface)]. The v4 approach is to declare the token in @theme and point it at a variable that changes per theme:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
:root {
--color-surface: #ffffff;
--color-text: #111827;
}
.dark {
--color-surface: #111827;
--color-text: #f9fafb;
}
@theme inline {
--color-surface: var(--color-surface);
--color-text: var(--color-text);
}This pattern has a catch. Two things named --color-surface in the same scope can conflict, so the example above is only a sketch of the idea. In practice, use different names for the runtime variable and the token. The code below is the version you should copy:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
:root {
--surface: #ffffff;
--text: #111827;
color-scheme: light;
}
.dark {
--surface: #111827;
--text: #f9fafb;
color-scheme: dark;
}
@theme inline {
--color-surface: var(--surface);
--color-text: var(--text);
}Now bg-surface and text-text are valid utilities, and they read the live variables. The inline keyword matters. It tells Tailwind to write var(--surface) directly into the generated utility instead of going through an intermediate variable, so the value follows whichever theme block is active.
This feature is specific to v4. In v3, you would instead map the colors in tailwind.config.js under theme.extend.colors, with values like 'var(--surface)'. The idea is the same.
Mixing variables with `dark:`
You do not have to choose one approach for the whole project. A common and practical split:
- Use variables for the shared palette: surfaces, text, borders. These change in every component.
- Use
dark:classes for one-off exceptions: a particular image that needsdark:brightness-90, or a badge whose dark color is unique.
<article class="bg-surface text-text border border-[var(--border)] p-4">
<img src="/photo.jpg" alt="Mountain lake" class="rounded dark:brightness-90" />
<button
class="mt-3 rounded bg-[var(--surface-raised)] px-3 py-1 hover:opacity-80 dark:hover:opacity-90"
>
Save
</button>
</article>Variants still stack as usual, so dark:hover:opacity-90 applies only when dark mode is active and the pointer is over the button.
System preference with variables
Variables also work with the default prefers-color-scheme strategy. Instead of a .dark class, use a media query:
:root {
--surface: #ffffff;
--text: #111827;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--surface: #111827;
--text: #f9fafb;
color-scheme: dark;
}
}If you also support a manual toggle, you need both the media query and the .dark rule, and you need to stop the media query from overriding an explicit light choice. One way is to scope the media rule to when no explicit choice exists, for example by marking the root with a data-theme attribute when the user chooses and writing the media rule as :root:not([data-theme]). This duplicates the dark values, which is the main cost of mixing the two strategies in plain CSS.
Edge cases and costs
- Opacity modifiers. In Tailwind v3,
bg-[var(--surface)]/50does not work with a hex value, because Tailwind cannot split avar()into channels. In v4, opacity on theme colors is handled withcolor-mix, sobg-surface/50works. In v3, you can store channels (--surface: 255 255 255) and write the config color asrgb(var(--surface) / <alpha-value>). - Debugging. Variable values are visible in the browser's computed styles panel. Look at the element, find
--surface, and see which rule supplied it. This is often faster than hunting through paired classes. - Third-party components. Libraries that hard-code colors will ignore your variables. You can override their styles, or wrap them with
dark:exceptions. - Missing variable. If
var(--surface)has no definition, the declaration is invalid at computed-value time and the property falls back to its inherited or initial value. A typo in a variable name fails quietly. Supply a fallback when it matters:bg-[var(--surface,#ffffff)]. - Flash of wrong theme. Variables do not remove the need to set the
.darkclass early. The flash-prevention script from the earlier chapter is still required.
When to use which approach
| Situation | Better choice |
|---|---|
| Small site, a handful of colored elements | Plain `dark:` classes |
| Many components share the same palette | CSS variables |
| Design system with brand themes beyond light and dark | CSS variables |
| One element needs a unique dark treatment | `dark:` class on that element |
| You want the markup to show every color decision | Plain `dark:` classes |
The practical rule: start with dark: classes. When you notice the same pair repeated across many files, extract that pair into a variable.
Exercise
Your stylesheet defines --surface on :root as white and in .dark as near-black. A component uses class="bg-[var(--surface)]". The user toggles to dark mode and the .dark class is correctly added to <html>, but the component stays white. Name two likely causes.
Show answer
First, the variable name may be misspelled in the class or in the .dark rule. A mismatch makes var() resolve to nothing or to the light value. Second, the component, or an ancestor, may redefine --surface locally, for example with an inline style or a more specific rule. That local value overrides the inherited one from .dark. Inspecting the computed value of --surface on the element in the browser's developer tools shows which rule supplies it.
Exercise
Why does the Tailwind v4 @theme example use inline, and why are the runtime variables (--surface) named differently from the token (--color-surface)?
Show answer
inline makes Tailwind write var(--surface) directly into each generated utility, so the utility reads the live variable and follows the active theme. Using different names avoids a self-reference, where --color-surface: var(--color-surface) would point at itself and resolve to nothing.