Part 43: Dark Mode in Tailwind: Media Query vs Class Strategy
Dark mode is a standard expectation in modern software design. Tailwind provides first-class support via the dark:* variant.
1. Strategy A: Operating System Preference (media)
By default, Tailwind uses the CSS prefers-color-scheme media query. Whenever the user's OS is in dark mode, dark:* styles activate automatically:
<div class="bg-white dark:bg-slate-900 text-slate-900 dark:text-white p-6 rounded-xl">
Automatic Dark Mode
</div>
2. Strategy B: Manual Toggle via CSS Class (class or selector)
In most production apps, you want a toggle switch that allows users to override their OS preference. In tailwind.config.js:
module.exports = {
darkMode: 'class', // or 'selector' in Tailwind v3.4+
// ...
}
Now, dark:* classes only activate when a .dark class is present on the root <html> tag:
<!-- Light Mode -->
<html>
<body class="bg-white dark:bg-slate-900 text-slate-900 dark:text-white">...</body>
</html>
<!-- Dark Mode Active -->
<html class="dark">
<body class="bg-white dark:bg-slate-900 text-slate-900 dark:text-white">...</body>
</html>
Key Takeaways
- Use
darkMode: 'class'when you provide an in-app toggle switch. - Prefix any background, text, or border utility with
dark:to style dark mode effortlessly.
In Part 44, we will build a Flawless Dark Mode Toggle with LocalStorage and Anti-Flicker Script!

