In this little article, we will discuss about the new css function : light-dark()
What is light-dark() function?
Refered to MDN web docs :
" The light-dark()
CSS <color>
function enables setting two colors for a property - returning one of the two colors options by detecting if the developer has set a light or dark color scheme or the user has requested light or dark color theme - without needing to encase the theme colors within a prefers-color-scheme
media feature query. Users are able to indicate their color-scheme preference through their operating system settings (e.g. light or dark mode) or their user agent settings. The light-dark()
function enables providing two color values where any <color>
value is accepted. The light-dark()
CSS color function returns the first value if the user's preference is set to light
or if no preference is set and the second value if the user's preference is set to dark
. "
Why light-dark() function ?
Instead of duplicating classes in dark theme and light theme also sometimes in other custom themes too, light-dark() enables us to define a class one time and give it the colors we want for it, whether in light or dark mode also in other custom mode when it applies
How to use light-dark() css function ?
Let take this example :
/* Named color values */
:root {
color-scheme: light dark;
}
body {
/*when the theme is light it will take the first argument
and the second argument when the theme is light*/
color: light-dark(#333b3c, #efefec);
background-color: light-dark(#efedea, #223a2c);
}
Browser compatibility
As this function is new, by now it's supported by firefox, in other to use it on firefox you must have at least firefox version 120 or up, otherwise it will not work
As this feature is not supported by much browsers, it's not recommended to use it in your apps that are in production because it's not stable yet
Conclusion
If you have implemented the switch-theme system before, you know how boring is to configure that in projects, but now that comes to the end with the help of this new function : light-dark(), Now you can define one class and give values that it can take in all theme dynamically
Thank you for taking your time
HAPPY CODING !