DEV Community

Cover image for The Cleanest Way to Support Dark Mode using CSS Variables and Tailwind
Kittichote Kamalapirat
Kittichote Kamalapirat

Posted on

The Cleanest Way to Support Dark Mode using CSS Variables and Tailwind

Intro

To support dark mode with Tailwind, you would usually write something like this according to the docs.

<div className="bg-black dark:bg-white">
  <p className="text-white dark:text-black">text</p>
</div>
Enter fullscreen mode Exit fullscreen mode

This makes your already-long tailwind classes become even longer.

To fix this, we can use semantic colors and change colors dynamically based on the current theme. (semantic colors mean colors that are named based on their purposes, like success, warning, background, and primary)

Steps

In index.html, make sure you can toggle the class dark.
When dark mode is on.

<html class="dark" />
Enter fullscreen mode Exit fullscreen mode

When dark mode is off.

<html />
Enter fullscreen mode Exit fullscreen mode

Note: In a real project, you might want to detect the user preference using window.matchMedia("(prefers-color-schema: dark));

In your globals.css or any css files

:root {
    --color-foreground-primary: black;
    --color-background-primary: white;
}

.dark {
    --color-foreground-primary: white;
    --color-background-primary: black;
}
Enter fullscreen mode Exit fullscreen mode

By adding this, the variables will dynamically change when the website is in dark mode.

And in tailwind.config.js.

...
theme: {
    extend: {
      colors: {
        foreground: {
          primary: "var(--color-foreground-primary)",
        },
        background: {
          primary: "var(--color-background-primary)",
        },
      },
    },
  },
...
Enter fullscreen mode Exit fullscreen mode

Now, in your html, you can do the following.

<div className="bg-background-primary">
  <p className="text-foreground-primary">text</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Hope this is useful to you.

Let me know how you support dark mode in your projects!

Top comments (0)