
The problem
To support dark mode with Tailwind, the docs have you write something like this:
<div className="bg-black dark:bg-white">
<p className="text-white dark:text-black">text</p>
</div>
That makes your already long Tailwind classes even longer, and every color has to be written twice.
The fix is semantic colors: colors named for their purpose, like background, primary, success or warning, whose actual values change with the current theme.
Step 1: toggle a class
Make sure you can put a dark class on the <html> element.
<!-- dark mode on -->
<html class="dark">
<!-- dark mode off -->
<html>
window.matchMedia("(prefers-color-scheme: dark)") and let them override it.Step 2: define the variables
In globals.css, or any CSS file, give each semantic color one value for light mode and another for dark mode:
:root {
--color-foreground-primary: black;
--color-background-primary: white;
}
.dark {
--color-foreground-primary: white;
--color-background-primary: black;
}
Now the variables change on their own whenever the page is in dark mode.
Step 3: point Tailwind at them
theme: {
extend: {
colors: {
foreground: {
primary: "var(--color-foreground-primary)",
},
background: {
primary: "var(--color-background-primary)",
},
},
},
},
The result
One class per color, and it works in both themes:
<div className="bg-background-primary">
<p className="text-foreground-primary">text</p>
</div>
Try it. This box is built the same way: the card only uses CSS variables, and the switch just adds or removes one dark class.
Hello from a semantic card
No dark: classes anywhere. The colors come from four CSS variables.
Primary buttonHope this is useful. How do you handle dark mode in your projects?