A dark: Variant That Just Works
Dark Mode
Prefix any utility with the dark variant to apply it when dark mode is active, choosing a media or selector strategy.
What you'll learn
- Use the dark variant
- Switch between media and selector strategies
- Wire a manual theme toggle
Dark mode is built in. Prefix any utility with dark: and it applies only when dark mode is active.
The dark: Variant
<div class="bg-white text-gray-900 dark:bg-gray-900 dark:text-gray-100 p-6">
Readable in both themes.
</div> By default, dark: follows the operating system via prefers-color-scheme. With no extra setup, your site respects the user’s OS choice automatically.
Switching to a Selector Strategy
A media-only strategy cannot offer an in-app toggle. To drive dark mode from a class instead, override the dark variant in CSS:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *)); Now dark: activates whenever a .dark class is present on an ancestor — typically the <html> element — instead of reading the OS setting.
Wiring a Toggle
With the selector strategy, a tiny script toggles .dark and remembers the choice:
const root = document.documentElement
const stored = localStorage.theme
if (stored === 'dark' ||
(!stored && matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark')
}
function toggleTheme() {
const isDark = root.classList.toggle('dark')
localStorage.theme = isDark ? 'dark' : 'light'
} Run the first block as early as possible (an inline script in <head>) so the page never flashes the wrong theme before hydration. The toggle function then switches .dark and persists the preference for next visit.