Tailwind CSS cookbook · Intermediate
Add a dark mode toggle
Let users switch between light and dark themes with a button, using Tailwind's dark variant.
Approach
Switch the dark variant to a class with @custom-variant, then toggle the class with a button. In a real app,
save the choice in localStorage and apply it in an inline <head> script to avoid a flash.
Solution
<style type="text/tailwindcss">
@custom-variant dark (&:where(.dark, .dark *));
</style>
<div id="app" class="bg-white p-6 text-slate-900 transition-colors dark:bg-slate-900 dark:text-slate-100">
<div class="flex items-center justify-between">
<p class="font-semibold">Theme demo</p>
<button onclick="document.getElementById('app').classList.toggle('dark')"
class="rounded-full px-4 py-1.5 text-sm font-medium ring-1 ring-slate-300 dark:ring-white/20">Toggle theme</button>
</div>
<p class="mt-3 text-sm text-slate-600 dark:text-slate-400">Every element uses dark: variants for its colours.</p>
</div>
Pitfalls
- Adding the class after the app loads causes a white flash on every page load.
- Low-contrast dark colours; use lighter text shades (
slate-300/400) on dark backgrounds.
Variations
- Offer three options (light, dark, system) and fall back to
prefers-color-schemefor "system". - Use semantic tokens in
@themethat switch value under.darkso components need fewerdark:classes.
Further reading: Tailwind CSS docs
Reference: https://tailwindcss.com/docs/dark-mode