Dark Mode Colors in CSS with light-dark()
Dark mode colors without duplicating values
You defined every variable in :root and again inside @media (prefers-color-scheme: dark). light-dark() holds both values in one place so you do not repeat yourself.
The old hack vs the modern fix
View demo:root {
--text: #111;
--bg: #fff;
}
@media (prefers-color-scheme: dark) {
:root {
--text: #eee;
--bg: #222;
}
}:root {
color-scheme: light dark;
color: light-dark(#111, #eee);
}Light dark browser support
Live demo
Why the modern way wins
No duplication
First argument is light, second is dark. One declaration, no @media block for each variable.
Works with variables
light-dark(var(--text-light), var(--text-dark)) fits right into a design token setup.
Any property
Use it for color, background, border-color, fill, stroke. Anything that takes a color.
- Lines Saved
- 12+ → 4
- No duplicate @media variables
- Old Approach
- :root + dark @media
- Re-declare every variable for dark
- Modern Approach
- light-dark()
- One value per scheme
How it works
The old approach was to set your colors (or CSS variables) in :root, then open a @media (prefers-color-scheme: dark) block and redeclare every variable or property for dark mode. That meant every color in two places and easy drift between light and dark.
The modern approach is light-dark(lightValue, darkValue). The browser picks the first or second value based on the element's used color-scheme. Set color-scheme: light dark so it follows the OS setting. Without it, light-dark() always returns the light value. That same declaration also makes form controls and scrollbars follow. You can use raw colors or variables: light-dark(var(--text), var(--text-dark)).