Sub topic 3
Saving the Choice and Preventing a Flash of the Wrong Theme
Assume basic CSS selectors, the cascade, and JavaScript DOM attributes. The goal is to support three choices: light, dark, and system. The system choice follows prefers-color-scheme.
Read localStorage in the document head, before the main stylesheet is applied. This sets the root attribute before the first paint:
<script>
const saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.dataset.theme = saved;
}
</script>Your CSS can then use [data-theme] to override the automatic system theme. A toggle should save only explicit choices. For a system option, remove the saved value and the attribute:
function setTheme(theme) {
if (theme === "system") {
localStorage.removeItem("theme");
delete document.documentElement.dataset.theme;
} else {
document.documentElement.dataset.theme = theme;
localStorage.setItem("theme", theme);
}
}Designing a Comfortable Dark Palette
Dark mode does not require pure black. Use a dark gray background and slightly lighter surfaces. Avoid pure white text because it can cause glare.
Keep colors semantic, such as --bg, --surface, --text, and --muted-text. Components then use roles instead of hard-coded colors, making both themes consistent.
Checking Contrast and Accessibility
Normal text should have a contrast ratio of at least 4.5:1. Large text needs at least 3:1. Check body text, muted text, links, borders, and focus indicators separately. Never communicate state by color alone.
Adapting Images and Media
Use alternate assets when an image contains a logo or text:
<picture>
<source srcset="logo-dark.png" media="(prefers-color-scheme: dark)">
<img src="logo-light.png" alt="Company logo">
</picture>For ordinary photos, a small brightness reduction may reduce glare, but do not hide meaningful details.
Testing and Browser UI
In developer tools, emulate both prefers-color-scheme: light and dark. Test a fresh visit, each manual choice, reloads, and switching back to system. Inspect the root attribute and stored value when debugging.
Match browser controls and address-bar UI with theme-color metadata:
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#121212" media="(prefers-color-scheme: dark)">Exercise
What should the system option do when the user previously selected dark mode?
Show answer
Remove the saved theme value and the data-theme attribute so CSS can follow the current system preference.