Sub topic 2
Configuring Dark Mode in Tailwind v3 and v4
Assume you know basic HTML, CSS, Tailwind utilities, JavaScript, and localStorage. Tailwind’s dark: variant adds styles when dark mode is active.
Configure the dark variant
Tailwind v3 uses the operating system preference by default. The browser checks prefers-color-scheme: dark:
<div class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<h1 class="text-2xl font-bold">Dashboard</h1>
<p class="text-gray-600 dark:text-gray-300">System-controlled theme.</p>
</div>For a manual toggle, configure a selector strategy in Tailwind v3.4.1 or later:
// tailwind.config.js
module.exports = {
darkMode: "selector",
content: ["./src/**/*.{html,js}"],
};In earlier v3 releases, use darkMode: "class". Then place dark on an ancestor, commonly the root element:
<html class="dark">
<body class="bg-white dark:bg-gray-900">
...
</body>
</html>Tailwind v4 has no darkMode configuration option. Redefine the variant in your CSS:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));A data attribute is another option:
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));Combine variants
Variants can stack. This button changes its hover color only in dark mode:
<button class="bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 md:px-6">
Save
</button>dark:hover:bg-gray-700 requires both conditions: dark mode and pointer hover. Responsive variants such as md: can be combined similarly.
Build a persistent theme toggle
Store light or dark when the user makes an explicit choice. Remove the value to return to system behavior:
const root = document.documentElement;
const preference = localStorage.getItem("theme");
root.classList.toggle(
"dark",
preference === "dark" ||
(preference === null &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
function setTheme(theme) {
if (theme === "system") {
localStorage.removeItem("theme");
root.classList.toggle(
"dark",
window.matchMedia("(prefers-color-scheme: dark)").matches,
);
} else {
localStorage.setItem("theme", theme);
root.classList.toggle("dark", theme === "dark");
}
}Exercise
In Tailwind v4, what must you add before a dark: utility responds to a .dark class?
Show answer
Add @custom-variant dark (&:where(.dark, .dark *)); to the stylesheet, then place .dark on an ancestor.