CSS light-dark() Builder
Compose a CSS light-dark() rule with a color-scheme opt-in.
Overview
The CSS light-dark() Builder composes a light-dark(light-value, dark-value) colour expression and pairs it with the required color-scheme declaration so the browser resolves the right variant per the user's OS preference or the page's selected theme. No JavaScript, no class toggling.
This is the modern alternative to per-property @media (prefers-color-scheme: dark) overrides. Useful for designers and developers learning how to support dark mode with CSS light-dark or how to opt into the user's preferred colour scheme without media queries.
How it works
CSS Color Module Level 5 defines light-dark(light, dark) which returns one of the two values based on the computed color-scheme property of the element (and ultimately the user agent's preference). To opt in, you must set color-scheme: light dark on :root — otherwise the function always resolves to the light value.
light-dark() works anywhere a <color> is expected, including custom properties. This means you can declare your tokens once (--surface: light-dark(white, #111)) and the whole stylesheet adapts automatically.
Examples
- Opt-in plus a tokenised surface →
:root { color-scheme: light dark; --bg: light-dark(white, #111); }. - Inline text colour →
color: light-dark(black, #f5f5f5);. - Border colour →
border: 1px solid light-dark(#e5e7eb, #374151);. - Forcing a section to follow a specific scheme → set
color-scheme: lighton the section.
FAQ
Does light-dark replace prefers-color-scheme media queries?
For colour values, yes. For larger structural changes (different background images, different layouts), media queries are still the right tool.
What if I forget to declare color-scheme?
The function resolves to the light value and dark mode never activates. Always declare color-scheme: light dark (or both) on :root.
Can the user override the OS preference?
Yes — your UI can write color-scheme: dark to an element to force dark mode for that subtree, useful for theme toggles.
Browser support?
All evergreen browsers as of mid-2024. For older browsers, provide a media-query fallback or use a class-based theming approach.