A Simpler Light and Dark Theme With CSS light-dark()
light-dark() lets you keep the light and dark versions of a color in one declaration. It is a small CSS feature, but it makes a theme easier to read because the two values sit next to each other.
There is one important setup step: tell the browser that the page supports both schemes.
:root {
color-scheme: light dark;
}
Now light-dark() can choose between its two arguments:
body {
background-color: light-dark(#f0f0f0, #222);
color: light-dark(#333, #fff);
}
The first value is used for a light color scheme and the second for a dark one. The active scheme normally follows the user’s preference, unless your page sets a different supported scheme on an element.
It replaces repetition, not design work
The function can remove a collection of repeated prefers-color-scheme media queries. It does not check contrast, choose good colors, or account for every image and component.
I like it most with custom properties:
:root {
color-scheme: light dark;
--surface: light-dark(#fff, #181818);
--text: light-dark(#222, #f5f5f5);
}
Because light-dark() was relatively new when this article was published, check current browser support before removing an existing fallback. Once support fits your audience, it is a much cleaner way to keep paired theme values together.