This is a Sass mixin to handle a 3-way dark mode. It relies on a data-theme
attribute on your <html>
element with a value of light
or dark
. If data-theme
is absent (i.e. it's neither light
nor dark
), the system's preferred mode is used.
body {
// matches data-theme="light" or data-theme="auto" with system instructing light mode
@include light {
background: white;
color: black;
}
// matches data-theme="dark" or data-theme="auto" with system instructing dark mode
@include dark {
background: black;
color: white;
}
}
See the example above on sassed
Caveat: This mixin targets modern browsers which support the :where()
pseudo selector. There is an older revision of this Gist with more caveats, but also with support for older browsers, which you can find here.
@wonsuc You're right. I was aware of that caveat, but didn't add it to the readme. Your case inspired me to adjust the mixins. They're slightly more complex now, but they also support pseudo elements like
::before
now.