Lesson 46 of 50
cssCSS for Dark Mode & Theming
9 mins
Course progress92%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 46 of 50
css9 mins
Keep these ideas in mind as you work through the lesson.
Dark mode isn’t just a colour swap – it requires a thoughtful palette, contrast checks, and a strategy for user‑initiated toggles.
prefers-color-scheme):root {
--bg:#fff; --text:#111; --primary:#0066cc;
}
@media (prefers-color-scheme: dark) {
:root { --bg:#111; --text:#eee; --primary:#4a90e2; }
}
body { background:var(--bg); color:var(--text); }
<button id="themeBtn">Toggle dark</button>
const btn = document.getElementById('themeBtn');
btn.addEventListener('click',()=>{
document.documentElement.dataset.theme =
document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
});
[data-theme="dark"] {
--bg:#111; --text:#eee; --primary:#4a90e2;
}
Changing the attribute swaps the entire colour palette instantly.
#000) – a dark gray (#111) reduces eye strain.#1e1e1e).image-set() with a dark variant) or use CSS filters (filter:invert(0.9) hue-rotate(180deg))..logo {
background:url('logo-light.svg') center/contain no-repeat;
}
@media (prefers-color-scheme: dark) {
.logo { background-image:url('logo-dark.svg'); }
}
Persist the choice in localStorage and apply it on page load:
const saved = localStorage.getItem('theme');
if (saved) document.documentElement.dataset.theme = saved;
btn.addEventListener('click',()=>{
const newTheme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = newTheme;
localStorage.setItem('theme', newTheme);
});
outline that adapts to the theme).prefers-color-scheme.--primary) updates the whole UI without rewriting each rule.prefers-color-scheme is supported in Chrome 76+, Safari 12.1+, Edge 79+, Firefox 67+. Older browsers fall back to the default light theme.