CSSMedium
How do you implement dark mode properly in CSS?
By FrontendPro Editorial Team Updated 8/7/2026
#css#theming#dark-mode
Answer
Combine the system preference with a manual override, driven by custom properties:
css
:root {
color-scheme: light dark;
--bg: #ffffff;
--fg: #111827;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #0b0f19; --fg: #e5e7eb; }
}
/* An explicit user choice must beat the media query */
:root[data-theme="light"] { --bg: #ffffff; --fg: #111827; }
:root[data-theme="dark"] { --bg: #0b0f19; --fg: #e5e7eb; }
body { background: var(--bg); color: var(--fg); }
color-scheme makes scrollbars and native form controls follow too. Set data-theme early (a blocking script in <head>) to avoid a white flash on load.
