Sub topic 3
Avoiding the Flash of the Wrong Theme
Assume you know basic HTML, CSS, JavaScript, and Tailwind variants. This chapter assumes a manual theme strategy where .dark controls the active theme.
Avoiding the flash of the wrong theme
A flash of the wrong theme happens when the browser paints the page before JavaScript adds or removes the dark class. Run the theme check inline in the document head, before the stylesheet loads.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
const saved = localStorage.getItem("theme");
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.classList.toggle(
"dark",
saved === "dark" || (saved === null && systemDark)
);
</script>
<link rel="stylesheet" href="/styles.css">
</head>
<body class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<main>Content</main>
</body>
</html>The browser now sees the correct class while it first renders the page.
Reducing repetition with CSS variables
Repeated dark: utilities can become difficult to maintain. Define semantic CSS variables instead. A semantic variable describes a role, such as --surface or --text, rather than a specific color.
:root {
--surface: #ffffff;
--text: #111827;
color-scheme: light;
}
.dark {
--surface: #111827;
--text: #f9fafb;
color-scheme: dark;
}Use the variables from Tailwind with an arbitrary value:
<section class="bg-[var(--surface)] text-[var(--text)]">
Theme-aware content
</section>Scrollbars and form controls with `color-scheme`
The color-scheme property tells the browser which native appearance to use for controls, scrollbars, and other built-in UI. Set it for both themes so a dark page does not contain bright native controls.
Checking contrast and accessibility
Check text against its background in both themes. Body text should generally meet a contrast ratio of 4.5:1. Large text has a lower 3:1 requirement. Do not communicate state through color alone. Keep visible focus styles, and test keyboard navigation in both themes.
When `dark:` classes do nothing
Check these common causes:
- In Tailwind v3, configure
darkMode: 'selector'or the older'class'setting. - In Tailwind v4, redefine the variant with
@custom-variant dark (&:where(.dark, .dark *));. - Confirm that
.darkis on an ancestor of the element. - Restart the development server after changing Tailwind configuration.
- Confirm the class name is not being removed by a template or script.
Exercise
Why should the theme script run in the document head?
Show answer
It adds the correct theme class before the browser paints the stylesheet and page, preventing a flash of the wrong theme.