A small feature that people notice and appreciate.
Direct answer
Define your colours as CSS variables, override them for dark mode, toggle a data-theme attribute on <html> with JavaScript and save the user's choice in localStorage. Use prefers-color-scheme as the default.
CSS
:root {
--bg: #ffffff;
--text: #111111;
}
:root[data-theme="dark"] {
--bg: #111111;
--text: #f5f5f5;
}
body {
background: var(--bg);
color: var(--text);
}
JavaScript
const root = document.documentElement;
const saved = localStorage.getItem("theme");
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
root.dataset.theme = saved || (prefersDark ? "dark" : "light");
document.querySelector("#toggle").addEventListener("click", () => {
const next = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
});
Tips
- Check contrast in both themes.
- Avoid a flash by setting the theme early in the page head.
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
Variables plus a data attribute plus localStorage makes a neat, small feature.



