← back to Shane
Tutorial2 min read

The cleanest way to support dark mode

Stop writing dark: on every Tailwind class. Name colors by what they're for, let CSS variables swap them, and let Tailwind read the variables.

Kittichote "Shane" Kamalapirat · December 2023

A laptop showing an app in dark mode next to a cup of coffee

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>
In a real project you'll probably start from the user's system setting with 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.

Live demo

Hello from a semantic card

No dark: classes anywhere. The colors come from four CSS variables.

Primary button
<div class="stage">

Hope this is useful. How do you handle dark mode in your projects?

Let's make
something fun.

Freelance, contract, or full-time. Serious work, unserious energy.

LinkedIn ↗ GitHub ↗ Toptal ↗