2 min read

CSS light-dark() Function

The light-dark() CSS function enables setting two colors for a property: one to be used when the user prefers a light color scheme, and the other for a dark color scheme. It simplifies implementing dark mode by reducing the need for verbose media queries.

1. Prerequisites

For light-dark() to work, you must explicitly tell the browser that your element (or the entire page) supports both light and dark color schemes. This is done using the color-scheme property.

:root {
  color-scheme: light dark;
}

If color-scheme is not set, light-dark() will always return the light value.

2. Syntax

property: light-dark(light-color, dark-color);
  • light-color: The color used when the used color scheme is light.
  • dark-color: The color used when the used color scheme is dark.

3. Basic Usage

Instead of writing separate variables inside media queries, you can define them inline or in the :root block.

The Old Way (Media Queries)

:root { --text: #333; }
@media (prefers-color-scheme: dark) {
  :root { --text: <a href='/?search=%23fff' class='obsidian-tag'>#fff</a>; }
}

The New Way (light-dark())

:root {
  color-scheme: light dark;
  --text: light-dark(#333, <a href='/?search=%23fff' class='obsidian-tag'>#fff</a>);
}

4. Section-Specific Themes

Because light-dark() reacts to the color-scheme property, you can force specific sections to be light or dark regardless of the system preference.

.dark-section {
  color-scheme: dark;
  /* This will use the dark value (#fff) even if system is light */
  color: light-dark(#333, <a href='/?search=%23fff' class='obsidian-tag'>#fff</a>); 
}

5. Browser Support

light-dark() is supported in modern versions of Chrome, Edge, Firefox, and Safari.

programming/css/css programming/css/colors-and-backgrounds programming/css/css-functions