How to add dark mode to a website the right way
Dark mode is a popular request, and modern CSS makes a solid implementation fairly approachable.
Step 1: use CSS custom properties for colors. Define your colors once, like --bg, --text and --accent, on :root, and use those variables everywhere instead of hard-coded colors. Switching themes then means changing a handful of values.
Step 2: respect the user's system setting. The prefers-color-scheme: dark media query lets you redefine those variables automatically when the user's device is in dark mode.
Step 3 (optional): add a manual toggle. Set an attribute like data-theme="dark" on the <html> element and save the choice in localStorage. Apply it as early as possible in page load to avoid a flash of the wrong theme.
Step 4: tell the browser. The color-scheme property helps built-in elements like scrollbars and form controls match your theme.
Common mistakes:
- Pure black backgrounds with pure white text, which many people find harsh. Slightly softened colors are often easier on the eyes.
- Forgetting images and icons. Logos with dark text can disappear; SVG icons using
currentColoradapt automatically. - Low contrast in one theme because colors were only checked in the other.
- Hard-coded colors left in a few components, so parts of the page don't switch.
Do you follow the system setting only, or always offer a toggle too? How do you handle images and charts in dark mode?
Comments · 2
Don't use pure black and pure white. Slightly softened colors are easier on the eyes and look more polished.
Respect prefers-color-scheme by default, and let users override with a toggle that you store in localStorage.