Sub topic 6
Building a theme toggle
This chapter assumes you know basic HTML, CSS and JavaScript (the DOM and localStorage), and that a Tailwind project is already set up. It also assumes you have read the previous chapters on the dark: variant and on configuring the class or selector strategy. A toggle only works once dark: is keyed to a .dark class on an ancestor element.
What a toggle does
With the manual strategy, Tailwind does not decide the theme. Your code does. A toggle has one job: add or remove the dark class on the <html> element. Every dark: utility in the page then switches on or off.
Putting the class on <html> (document.documentElement) is the usual choice. It sits above <body>, so every element is a descendant. It is also available while the page is still loading, which matters for the chapter on avoiding a flash of the wrong theme.
The core script
This script decides whether dark mode should be on, then sets the class to match.
// Run on page load and whenever the user changes the setting
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);classList.toggle(name, force) takes a second argument. When it is true, the class is added. When it is false, the class is removed. Passing a boolean makes the call safe to repeat, which a plain toggle is not.
The condition has two parts joined by ||:
localStorage.theme === "dark": the user explicitly chose dark.!("theme" in localStorage) && matchMedia(...): the user made no choice, and the operating system prefers dark.
If the user saved "light", both parts are false, so the class is removed. That is what makes light win over a dark system setting.
Saving the user's choice
Three assignments cover the three states. The next chapter builds the full light, dark and system switcher on top of them.
// User chooses light mode
localStorage.theme = "light";
// User chooses dark mode
localStorage.theme = "dark";
// User chooses to follow the system again
localStorage.removeItem("theme");Each assignment only stores a value. Nothing on the page changes until the core script runs again, so you must call it after every change.
A working toggle
Here is a complete page with a button that switches between light and dark. It wraps the core script in a function so the page load and the click handler can share it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/styles.css" />
</head>
<body class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<button
id="theme-toggle"
class="rounded bg-gray-100 px-3 py-1 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700"
>
Toggle theme
</button>
<script>
function applyTheme() {
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
}
document.getElementById("theme-toggle").addEventListener("click", () => {
const isDark = document.documentElement.classList.contains("dark");
localStorage.theme = isDark ? "light" : "dark";
applyTheme();
});
applyTheme();
</script>
</body>
</html>The click handler reads the current state from the DOM, stores the opposite value, and re-applies the theme. Reading the class instead of localStorage means the button works correctly on the first click, even when the theme came from the system setting and nothing is stored yet.
The button itself uses stacked variants: dark:hover:bg-gray-700 applies only when dark mode is active and the pointer is over the button.
Common errors
| Symptom | Likely cause |
|---|---|
| Button changes `localStorage` but the page does not change | `applyTheme()` was not called after the write |
| The class toggles in DevTools but `dark:` classes do nothing | The strategy is still `media`. Set `darkMode: 'selector'` in v3, or add `@custom-variant dark` in v4 |
| A saved "light" choice is ignored on a dark system | The condition checks only `matchMedia` and skips the `localStorage` test |
| The script throws on load | It runs before the button exists. Place it after the button, or wait for `DOMContentLoaded` |
Exercise
A user with a dark operating system setting has never visited your site. They click the toggle once. What value is stored in localStorage.theme, and why does the handler read the class instead of localStorage?
Show answer
The value "light" is stored. On the first visit nothing is stored in localStorage, but the page is already dark because the system prefers dark. The handler reads the current state from the dark class on <html>, sees it is present, and stores the opposite value. If it read localStorage instead, it would find nothing and could not tell that the page is currently dark.
Exercise
Why does the core script call classList.toggle("dark", condition) with a second argument instead of calling classList.toggle("dark") with no argument?
Show answer
With one argument, toggle flips the class every time it runs, so calling the script twice would undo the first call. With a boolean second argument, the class is added when the value is true and removed when it is false. The result depends only on the condition, so the script can safely run on page load and again after every change.