Dark Mode with Media Strategy in Tailwind CSS
Use the media strategy for Tailwind CSS dark mode to automatically follow the user's operating system color scheme preference with zero JavaScript.
General
Detailed Explanation
Dark Mode: Media Strategy
The media strategy uses the CSS prefers-color-scheme media query to automatically match the user's operating system preference. This requires zero JavaScript.
Configuration
// tailwind.config.js
module.exports = {
darkMode: "media",
// ...
};
In Tailwind v3, media is the default, so you can omit darkMode entirely.
Usage in HTML
<body class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
<h1 class="text-2xl font-bold">Hello</h1>
<p class="text-gray-600 dark:text-gray-400">
This text adapts to OS preference
</p>
</body>
How It Works Internally
Tailwind generates this CSS:
.bg-white { background-color: #fff; }
@media (prefers-color-scheme: dark) {
.dark\:bg-gray-900 { background-color: #111827; }
}
Advantages
- Zero JavaScript -- no toggle code, no localStorage
- No flash of wrong theme on page load
- Automatically updates when user changes OS preference
- Simpler implementation -- just add
dark:variants to your classes
Disadvantages
- Users cannot override their OS preference within your app
- No manual toggle button possible
- Less granular control
- Some users have OS set to light but prefer dark websites
Combining with JavaScript
You can detect the preference in JavaScript if needed:
const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
// Listen for changes
window.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (e) => {
console.log("Dark mode:", e.matches);
});
Use Case
Use the media strategy for simple sites, blogs, or documentation where you want dark mode to just work without any user interface for toggling.