Dark Mode with Class Strategy in Tailwind CSS
Configure Tailwind CSS dark mode using the class strategy for manual toggle control. Includes implementation patterns and theme switching code.
Colors
Detailed Explanation
Dark Mode: Class Strategy
Tailwind CSS supports two dark mode strategies: media (follows OS preference) and class (manual toggle). The class strategy gives you full programmatic control.
Configuration
// tailwind.config.js
module.exports = {
darkMode: "class",
// ...
};
How It Works
When darkMode is set to "class", Tailwind generates dark variants that activate when the dark class is present on the <html> element:
<html class="dark">
<body class="bg-white dark:bg-gray-900">
<p class="text-gray-900 dark:text-gray-100">
Hello world
</p>
</body>
</html>
Implementing a Theme Toggle
// Simple toggle function
function toggleDarkMode() {
document.documentElement.classList.toggle("dark");
const isDark = document.documentElement.classList.contains("dark");
localStorage.setItem("theme", isDark ? "dark" : "light");
}
// Restore on page load
const theme = localStorage.getItem("theme");
if (theme === "dark" || (!theme && window.matchMedia("(prefers-color-scheme: dark)").matches)) {
document.documentElement.classList.add("dark");
}
Class vs Media
| Feature | Class | Media |
|---|---|---|
| User toggle | Yes | No |
| OS preference | Manual check | Automatic |
| SSR flash | Possible (fixable) | No |
| Granular control | Full | Limited |
The class strategy is recommended for most applications because it gives users a choice, which is better UX.
Use Case
Use the class strategy when you want to give users a dark/light theme toggle button in your application's header or settings.