Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new light-dark() function to switch theme color in CSS

We have many ways to switch between light and dark themes on the web. We can use JavaScript to switch between themes or we can use the prefers-color-scheme media query in CSS to switch between themes based on the user’s system preference.

The prefers-color-scheme media query lets us do things that would only be applied when light or dark mode is enabled on the user’s system. For instance, you can change the background color of the page to black when the user has enabled dark mode on their system like so.

body {
  background-color: white;
}

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

You can also change the color of the text based on the user’s system preference the same way.

The new light-dark() function

Now, to make this all more seamless, CSS is getting a new function called light-dark() which will let you specify two values for a property. The first value will be applied when the user has enabled light mode on their system and the second value will be applied when the user has enabled dark mode on their system.

Here’s how you can use it.

body {
  background-color: light-dark(#FFF, #000);
  color: light-dark(#333, #ccc);
}

As you can tell, we don’t need to use the prefers-color-scheme media query for the things like changing colors based on the preferred theme anymore. The light-dark() function will take care of that for us. And it’s also more granular as you can specify different values for different properties.

Apart from the user’s theme preference, the light-dark() function can also be used to switch between two values based on the color-scheme property.

The color-scheme CSS property allows an element to indicate which color schemes it can comfortably be rendered in.

That means, for light-dark() to work, you must also include a color-scheme declaration.

:root {
  color-scheme: light dark;
}

:root {
  --text-color: light-dark(#333, #ccc); 
  /* In Light Mode = return 1st value. 
  In Dark Mode = return 2nd value. */
}

You can also use the color-scheme property on a specific element so that it only applies to that element.

p {
  color-scheme: dark;
  background-color: light-dark(#FFF, #000);
}

Browser support

As for browser support, the light-dark() function is currently supported in Firefox 120 but hopefully, it will be supported in other browsers soon.

You can read more about the light-dark() function on its specification page here.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?