I want to support light and dark modes in my project.
I also want to have an 'inverted' mode, where I show a section of content in the opposite mode to the main site.
It's possible to use color-scheme: light dark;
to enable the light and dark theme in my document, and then light-dark()
to switch colours based on the active scheme:
html {
color-scheme: light dark;
background-color: light-dark(var(--white), var(--black));
}
(I use https://lightningcss.dev/ to convert this CSS to work in browsers that don't support light-dark
, so I'm going to ignore browser support from here on in).
Inverting the colour scheme is as simple as setting the opposite colour scheme on the invert
class:
@media (prefers-color-scheme: dark) {
.invert {
color-scheme: light;
}
}
@media (prefers-color-scheme: light) {
.invert {
color-scheme: dark;
}
}
This, with light-dark()
means that the browser will pick the opposite scheme to the active one insite the invert class, with no need to specify the vars on the invert class at all.
It's possible that this is really obvious, but it was a new realisation to me and I thought others might like to know about it :)
I expect I should make one of those fancy intereactive things to show it off, but hopefully you get the idea without it :)
This might not be an excellent idea for eveyone :) My use case is to do a full-width 'breakout' section that's lightly used. I wanted something that would contrast with the rest of the site in both modes, and it seemed flipping the colour scheme was a neat way to do this.