Sub topic 6
Building a theme toggle
This chapter builds a button that switches a page between light and dark. It assumes you know basic HTML and CSS, Tailwind utility classes and variants such as hover: and md:, and the DOM and localStorage in JavaScript. It also assumes a project with Tailwind already installed. Earlier chapters covered the dark: variant and the difference between following the operating system and using a manual strategy. Here you wire up the manual strategy.
A toggle has three parts. A configuration makes dark: depend on a class. A script adds or removes that class. A button calls the script. Later chapters add a third "system" choice and remove the flash of the wrong theme on load. This chapter produces a working two-state toggle that remembers its choice.
How the pieces fit
Tailwind does not know about your button. It only generates CSS rules such as "apply this background when an ancestor has the dark class". Your JavaScript decides when that class exists. Putting the class on the <html> element means every element on the page is a descendant, so every dark: utility can respond.
Step 1: make `dark:` depend on a class
By default, dark: follows prefers-color-scheme, so adding a class changes nothing. Switch the strategy first. The setting depends on your Tailwind version.
In Tailwind v3.4.1 and later, set darkMode to 'selector'. Earlier v3 releases use 'class'.
// tailwind.config.js (Tailwind v3.4.1 and later)
module.exports = {
darkMode: 'selector', // use 'class' in earlier v3 versions
content: ['./src/**/*.{html,js}'],
};Tailwind v4 has no darkMode option. You redefine the variant in your CSS instead.
/* Tailwind v4 */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));The selector &:where(.dark, .dark *) matches an element that has the dark class or sits inside an element that does. :where() adds no specificity, so dark: utilities keep their normal precedence against other utilities.
If you prefer a data attribute, v4 lets you key the variant to it. The script must then set data-theme="dark" instead of the class.
/* Tailwind v4, using a data attribute instead of a class */
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));This chapter uses the class version.
Step 2: write the markup
Style the page with pairs of utilities. The light value is unprefixed, and the dark value carries dark:.
<div class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<h1 class="text-2xl font-bold">Hello</h1>
<p class="text-gray-600 dark:text-gray-300">This card follows the active theme.</p>
</div>The toggle button needs to show different content in each theme. You can do that with the same variant: one icon is hidden in dark mode, and the other is hidden in light mode.
<button
id="theme-toggle"
type="button"
aria-pressed="false"
class="rounded bg-gray-100 px-3 py-1 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700"
>
<span class="dark:hidden">☀️ Light</span>
<span class="hidden dark:inline">🌙 Dark</span>
</button>The dark:hover:bg-gray-700 class shows that variants stack. It applies only when dark mode is active and the pointer is over the button.
The label text is a visible indicator, but screen reader users need a state too. The aria-pressed attribute tells assistive technology whether the button is "on". The script keeps it in sync.
Step 3: write the script
The script has to do four things:
- Work out the starting theme.
- Apply a theme to the page.
- Flip the theme when the button is clicked.
- Save the choice.
const root = document.documentElement;
const button = document.getElementById("theme-toggle");
function readSavedTheme() {
try {
return localStorage.getItem("theme");
} catch {
return null; // storage blocked, for example by browser privacy settings
}
}
function saveTheme(theme) {
try {
localStorage.setItem("theme", theme);
} catch {
// The toggle still works for this visit, but the choice is not remembered.
}
}
function applyTheme(isDark) {
root.classList.toggle("dark", isDark);
button.setAttribute("aria-pressed", String(isDark));
}
const saved = readSavedTheme();
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
applyTheme(saved === "dark" || (saved === null && prefersDark));
button.addEventListener("click", () => {
const nextIsDark = !root.classList.contains("dark");
applyTheme(nextIsDark);
saveTheme(nextIsDark ? "dark" : "light");
});Three details matter here.
classList.toggle("dark", isDark)takes a second argument. With the argument, it forces the class on or off. Without it, it flips the class. Forcing is safer inapplyThemebecause calling the function twice with the same value cannot undo itself.- The click handler reads the page, not a variable. It checks
root.classList.contains("dark"). The DOM is the single source of truth, so the button stays correct even if another script changes the class. - The initial theme uses the saved choice first. With nothing saved, it falls back to the operating system preference. A first-time visitor on a dark system therefore sees dark mode, and their first click switches to light.
The try/catch wrappers matter because localStorage access can throw. This happens in some private browsing modes, with blocked cookies, or in sandboxed iframes. An uncaught exception at the top of your script would stop the whole toggle from loading.
A complete page you can run
This page loads Tailwind v4 from the browser build, so you can save it as index.html and open it directly. It is for experiments, not production. In a real project you would use your build setup and the CSS shown in Step 1.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Theme toggle</title>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<style type="text/tailwindcss">
@custom-variant dark (&:where(.dark, .dark *));
</style>
</head>
<body class="min-h-screen bg-white p-8 text-gray-900 dark:bg-gray-900 dark:text-white">
<button
id="theme-toggle"
type="button"
aria-pressed="false"
class="rounded bg-gray-100 px-3 py-1 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700"
>
<span class="dark:hidden">☀️ Light</span>
<span class="hidden dark:inline">🌙 Dark</span>
</button>
<h1 class="mt-6 text-2xl font-bold">Hello</h1>
<p class="text-gray-600 dark:text-gray-300">This page follows the active theme.</p>
<script>
const root = document.documentElement;
const button = document.getElementById("theme-toggle");
function readSavedTheme() {
try {
return localStorage.getItem("theme");
} catch {
return null;
}
}
function saveTheme(theme) {
try {
localStorage.setItem("theme", theme);
} catch {}
}
function applyTheme(isDark) {
root.classList.toggle("dark", isDark);
button.setAttribute("aria-pressed", String(isDark));
}
const saved = readSavedTheme();
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
applyTheme(saved === "dark" || (saved === null && prefersDark));
button.addEventListener("click", () => {
const nextIsDark = !root.classList.contains("dark");
applyTheme(nextIsDark);
saveTheme(nextIsDark ? "dark" : "light");
});
</script>
</body>
</html>Reload the page after clicking. The theme should stay as you left it. You may see a brief flash of light before the script runs, because the script sits at the end of <body>. That flash is expected here, and the chapter on flash prevention fixes it.
Edge cases and common errors
The toggle does nothing
If clicking changes the dark class (check in the browser's element inspector) but the page does not change, the strategy was not switched. Tailwind is still using prefers-color-scheme. Recheck Step 1 for your version.
Do not mix versions of the setup. Putting darkMode: 'selector' in a v4 project has no effect, and a @custom-variant rule in a v3 project is not understood.
The class lands on the wrong element
The v4 variant &:where(.dark, .dark *) works on any ancestor, so putting dark on <body> still styles everything inside the body. Anything outside it does not respond, including the <html> background. Using <html> avoids that, and it is also the element where the early theme script in a later chapter can run before the body exists.
Saved values drift
The script treats any value other than "dark" as light. If another script or an older version of your site stored something else, such as "true" or "Dark", the page silently shows light mode. Always write exactly "light" or "dark", and read with an exact comparison as above.
The system preference is only read once
The starting theme is computed when the script runs. If a visitor has no saved choice and changes their operating system theme while the page is open, the page does not follow. Following live changes needs a change listener on the media query. The next chapter builds that along with a proper "system" option.
Two tabs disagree
Saving to localStorage does not update other open tabs. The browser fires a storage event in the other tabs, so you can sync them:
window.addEventListener("storage", (event) => {
if (event.key === "theme") {
applyTheme(event.newValue === "dark");
}
});This is optional. It is worth adding on sites where people keep many tabs open.
Design choices
| Choice | Option A | Option B | Consider |
|---|---|---|---|
| Where to put the state | Class on `<html>` | `data-theme` attribute | A class is the default and works in v3 and v4. An attribute can carry more than two values, which suits multiple themes. |
| Button label | Static label plus `aria-pressed` | Label that changes with the theme | Use one pattern. A label that says "Dark mode" while also pressed can read as contradictory to screen readers. |
| Source of truth | The DOM class | A JavaScript variable | The DOM stays correct when other code changes the class. |
Summary of the working model
dark:only reacts to the class when the configuration says so.- The class belongs on
<html>. - One function sets the class and the
aria-pressedstate, and the click handler reads the current state from the DOM. - Storage calls are wrapped in
try/catchbecause they can fail. - Reading the saved value, then the system preference, gives sensible first-visit behavior.
Exercise
A teammate on a Tailwind v4 project adds darkMode: 'selector' to a config file, and a toggle script that adds the dark class to <html>. Clicking the button changes the class in the inspector, but no styles change. What is missing, and what exact CSS line fixes it?
Show answer
Tailwind v4 has no darkMode option, so the setting is ignored and dark: still follows prefers-color-scheme. Add a custom variant in the main CSS file after the import: @custom-variant dark (&:where(.dark, .dark *));. With that line in place, the dark class on <html> activates the dark: utilities.
Exercise
In the script above, why does the click handler compute the next theme with root.classList.contains("dark") instead of keeping a let isDark variable?
Show answer
The DOM class is what Tailwind actually reads, so it is the true state. A separate variable can fall out of sync if another script, the storage listener, or a later chapter's system-preference code changes the class. Reading the class each time means the button always flips from what the user currently sees.
Exercise
A visitor opens your page in a browser where localStorage access throws an error. What happens with the script in this chapter, and what would happen if the try/catch blocks were removed?
Show answer
With the try/catch blocks, reading returns null, so the page starts from the system preference. Clicking still toggles the theme for the current visit, but nothing is saved. Without them, the uncaught exception would stop the script at the first storage call, so the initial theme would never be applied, the click listener would never be attached, and the button would do nothing.