Dark mode on a website: build a theme toggle in 10 minutes
How to add dark mode: CSS variables, the prefers-color-scheme system setting, remembering the choice and a beautiful animated toggle.

Almost everyone expects dark mode: many enable it in the system and expect sites to follow. It is easier than it seems.
Step 1. Colors in variables
:root { --bg: #f6f6f4; --text: #0b0b0c; }
[data-theme="dark"] { --bg: #0b0b0c; --text: #f2f2f4; }
body { background: var(--bg); color: var(--text); }Step 2. System theme by default
const saved = localStorage.getItem('theme');
const dark = matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.dataset.theme = saved || (dark ? 'dark' : 'light');Step 3. The toggle
A button switches the attribute and saves the choice. Add a soft 300–500 ms transition so the switch is not harsh.

Common mistakes
- The site flashes light on load: put the theme script in head.
- White-background images glare in dark mode: prepare dark or transparent versions.
- Pure black and pure white are tiring: use softened shades.
Animated theme toggles are in the catalog for Tilda, Framer and Webflow.




