Customization and ThemingLesson 5.2
Tailwind dark mode: class strategy vs media strategy
darkMode class config, darkMode media config, dark: prefix, toggling dark class on html element, dark mode color pairs, dark mode localStorage, system preference
Tailwind Dark Mode
Tailwind dark mode uses the dark: prefix. Two strategies: class (you control toggling via JavaScript) or media (follows OS preference automatically).
Config
// tailwind.config.js
export default {
darkMode: "class", // or "media"
}Dark mode utilities
<body class="bg-white dark:bg-gray-950 text-gray-900 dark:text-gray-100">
<nav class="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
<span class="text-gray-900 dark:text-white font-semibold">Logo</span>
</nav>
<div class="bg-white dark:bg-gray-800 rounded-xl p-6">
<h2 class="text-gray-900 dark:text-white">Card title</h2>
</div>
</body>Toggling with JavaScript
const html = document.documentElement;
const toggle = document.getElementById("theme-toggle");
if (localStorage.theme === "dark") html.classList.add("dark");
toggle.addEventListener("click", () => {
html.classList.toggle("dark");
localStorage.theme = html.classList.contains("dark") ? "dark" : "light";
});Use class strategy for full user control and persistence. Use media when you always want to follow the OS. You cannot combine both natively — pick one per project.
