Modern websites often implement a dark mode to improve the user experience, reduce visual fatigue, and increase accessibility. Since browser dark modes only affect the browser interface, a website remains unchanged unless it has its own dark-mode styles.
In this article, I will show you how to implement a dark mode with Tailwind CSS that can be toggled on and off with a button, including user preference storage.
Why Tailwind for Dark Mode?
With Tailwind, you define dark variants directly on the component. You simply add a second class with the dark: prefix — that’s it. This keeps the code organized and avoids duplicate stylesheets.
Enable Dark Mode with a Class Selector
By default, Tailwind follows the operating system setting (prefers-color-scheme). If you want to be able to switch it manually, you can activate dark mode using a class selector. Add the following to your Tailwind input file:
src/input.css
@import "tailwindcss";
/* Activates dark: on all descendants as soon as .dark appears in the DOM */
@custom-variant dark (&:where(.dark, .dark *));
You can now define Light and Dark styles side by side:
HTML
Works even upside down
Works in any position even in space.
Toggle Button (with Label Change)
Using JavaScript, we add or remove the dark class from the html root element and store the choice in localStorage. This means the setting is preserved even after navigating to another page. We also change the button label from “Dark Mode” to “Light Mode.”
Button (HTML)
JavaScript
