More CSS features: light-dark()

Tags:

Providing a dark mode is good form nowadays. I like doing/having that too.

Light mode

Usually, a dark mode is done by switching to a second CSS sheet or having a CSS selector switching between a bright and a dark colour set using JS or the browser preferences. This can lead to some rule repetition:

.light-theme textarea {
    color: black;
    background-color: #8dfece;
}

.dark-theme textarea {
    color: #62b190;
    background-color: black;
}

Dark mode

CSS also has a function to do this color switching on an element without needing to repeat the declaration in a second rule: light-dark(color1, color2) will return color1 if the light environment is preferred by the user and color2 if the dark environment is preferred.

textarea {
    color: light-dark( black, black );
    background-color: light-dark( #8dfece, #62b190 );
}

You still might want to give the user an option to set their preference only for your website, storing that in a cookie. Bootstrap 5 itself has a fairly thorough, live-switching setup for that, but it's also somewhat long. There also is a short JS snippet on Github which is mildly simpler to integrate, but which only does the switching on page load or toggling of the user selection, and not when the user switches their browsers preference.