Day 107: the light-dark() color function
posted on
It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.
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>
Check out Day 61 to learn more about the color-scheme
property.
Further reading
Overview: 100 Days Of More Or Less Modern CSS