Jan's Development Microblog
Go back to blog overview
| Jan Valkenburg | CSS | Reading time: 3 min

What is the new light‑dark() attribute?

The new light-dark() attribute just launched in Firefox, this method simplifies the way you can apply light-dark mode colors to your website.

This attribute is a function that helps you to assign light and dark mode values to an attribute. At this point in time, Firefox is the only browser that supports it. But I assume other browsers will follow soon, possibly at the start of 2024.

What is the light-dark() attribute?

The light-dark() function is a new CSS attribute that allows us to define a color for light and dark mode on a single line. You can think of it as a helper function. This CSS attribute communicates with your operating system's dark or light settings to display colors based on whether you have enabled dark mode. The light-dark() function is an alternative to the prefers-color-scheme media queries.

@media (prefers-color-scheme: dark) {
    body {
        color: white;
        background-color: black;
    }
}

@media (prefers-color-scheme: light) {
    body {
        color: black;
        background-color: white;
    }
}

How do we use light-dark()?

To use the light-dark() color method, we should set the value of color-scheme in the :root to "light dark," as seen in the example below. Then, we can define the colors we want in the lines below using the light-dark method. Try to use this attribute sparely, to keep our CSS code clean. I believe the best place to use this attribute is in the :root element to combine it with CSS variables or on the body. The same goes for the prefers-color-scheme media queries.

:root {
    color-scheme: light dark;
}

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

Looking at the code above in light mode, the background will be white, and the text will be black. In dark mode, the background is black, and the text is white.

Final words

From my point of view, I think this function might be useful. However, there is too much focus on only light and dark mode, while other color modes might already exist. So, I think this method should be extendable with other color modes.

To end this blog I will include an inspiring quote from the Japanese anime series `My Hero Academia` based on the topic of this post. Light and darkness.

「星は闇なしでは輝けない。」— Stars can't shine without darkness. -- My Hero Academia.