rss_feed

New CSS Function: light-dark()

April 12, 2024
CSS light-dark() function
CSS light-dark() function

A few days ago, I stumbled across a new function in CSS that is going to make my life a tremendous amount easier: light-dark(). This function will enable developers to define both light and dark colors for a property in a single line without media queries.

Most websites I have worked on in the past several years have supported both light and dark modes based on the user’s preference. So far, I’ve achieved this by using the prefers-color-scheme media condition like in this example:

.example {
  color: #000000;

  @media (prefers-color-scheme: dark) {
    color: #ffffff;
  }
}

This works but requires several extra lines of code. The new light-dark() function will turn this into one-liner:

.example {
  color: light-dark(#000000, #ffffff);
}

So much cleaner and easier to read! That is especially the case if you have a large CSS class with multiple properties. The only prerequisite is that you set the color scheme in :root so that the browser knows your website supports both light and dark modes.

Here is the complete example:

:root {
  color-scheme: light dark;
}

.example {
  color: light-dark(#000000, #ffffff);
}

Once you’ve set color-scheme, you can use the light-dark() function anywhere in your CSS code.

The function is still relatively new and is therefore not available yet in every browser. I suspect it won’t take long for the holdouts to support it though since Google Chrome already supports it and Edge and Opera are also based on Chromium. Firefox supports it already and it’s already in development for Safari. You can see the browser compatibility list from MDN here:

Browser compatibility for light-dark()
Browser compatibility for light-dark() as of this writing

I am certainly looking forward to being able to write clearer, more concise CSS in the future using light-dark(). If you would like to read more details about it, there are a couple of links below.

Links

How would you rate this post?

About the Author

Alex Seifert
Alex is a developer, a drummer and an amateur historian. He enjoys being on the stage in front of a large crowd, but also sitting in a room alone, programming something or writing about technology and history.

Related Posts

Post a Comment

Your email is kept private. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Support Developer's Notebook

If you enjoyed this article, please consider contributing to Developer's Notebook so that we can continue writing about the topics we love.

Support Us →

Thank you!

— Alex Seifert, Founder and Writer