Loading lessons...
Dark Mode
Dark Mode
Tailwind includes a dark variant so you can style your site differently when dark mode is enabled.
Using the dark variant
<div class="bg-white dark:bg-gray-800 rounded-lg px-6 py-8 shadow-xl">
<h3 class="text-gray-900 dark:text-white">Writes upside-down</h3>
<p class="text-gray-500 dark:text-gray-400">...</p>
</div>
By default, dark follows the prefers-color-scheme media feature.
Toggling dark mode manually
Override the dark variant to use a CSS selector instead of the media query:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
Now dark:* utilities apply whenever the dark class is present:
<html class="dark">
<body>
<div class="bg-white dark:bg-black">...</div>
</body>
</html>
Using a data attribute
Override with an attribute selector instead:
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
<html data-theme="dark">...</html>
System theme support
For a three-way toggle (light / dark / system), use matchMedia and localStorage:
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches)
);
TL;DR
- Use
dark:to style in dark mode. - Default follows
prefers-color-scheme. - Override with
@custom-variant darkfor manual toggling. - A tiny script +
localStoragesupports a system toggle.