Dark Mode
Tailwind ships dark: variants out of the box. Toggle a .dark class on <html> (or use the OS preference) and every dark: utility kicks in.
Three steps to dark mode
EXAMPLE
<!-- 1. CSS-first config (v4) -->
@import 'tailwindcss';
@custom-variant dark (&:where(.dark, .dark *));
<!-- 2. Add dark: utilities in markup -->
<div class="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100">
<h1 class="text-2xl">Hello</h1>
<button class="bg-emerald-500 dark:bg-emerald-600 text-white px-4 py-2 rounded">
Save
</button>
</div>
<!-- 3. Toggle on the root element with JS -->
<script>
const root = document.documentElement;
const stored = localStorage.theme;
const dark = stored === 'dark'
|| (!stored && matchMedia('(prefers-color-scheme: dark)').matches);
root.classList.toggle('dark', dark);
function toggleTheme() {
const next = !root.classList.contains('dark');
root.classList.toggle('dark', next);
localStorage.theme = next ? 'dark' : 'light';
}
</script>
Why it matters
Apply dark: only to colour utilities (bg, text, border, ring). Spacing and layout should stay consistent — only the palette changes.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
<!-- enable: darkMode: 'class' in config --> <div class="bg-white dark:bg-slate-900 text-slate-900 dark:text-white">Adapts</div>Try it Yourself »
Exercise
Make a div white in light, slate-900 in dark.
class="bg-white
:bg-slate-900"
Four letters.
Discussion
Loading…