New Jul 19, 2024

Day 107: the light-dark() color function

More Front-end Bloggers All from Manuel Matuzović - Blog View Day 107: the light-dark() color function on matuzo.at

The light-dark() color function allows you to define two values for a color property. The property uses the first value when the color scheme is light or unknown and the second when it's dark.

For the function to work, you must define the available color schemes for the element. Apply it to the html element if you want it to work on the entire page.

html {
  --black: oklch(0% 0 0);
  --white: oklch(100% 0 0);

color-scheme: light dark; }

body { background-color: light-dark(var(--white), var(--black)); color: light-dark(var(--black), var(--white)); }

If you change the color scheme in your operating system to dark or light, the color and background-color properties in CSS now use the appropriate color. That eliminates the need for the prefers-color-scheme media feature for these tasks.

You can also force a specific type of color by setting the color-scheme property explicitly.

div {
  color-scheme: dark;

background-color: light-dark(var(--white), var(--black)); color: light-dark(var(--black), var(--white)); }

<div>
  My color scheme is always dark.
</div>
My color scheme is always dark.

Check out Day 61 to learn more about the color-scheme property.

My blog doesn't support comments yet, but you can reply via blog@matuzo.at.

Scroll to top