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.
I seem to be having an issue getting this to work, dark mode works, but I can't seem to use light mode.
My site is deployed here: https://listen2gether.github.io/
Here's the mixin you defined (converted to Sass, I only include the dark mixin as I want to default to light theme):
https://github.com/Listen2gether/Listen2gether.github.io/blob/develop/src/templates/sass/include/_themes.sass
Here is an example of where I use the dark mixin:
https://github.com/Listen2gether/Listen2gether.github.io/blob/61506d4feae3d4a525df4e8698d2c5c223a28e42/src/templates/sass/general.sass#L11
In my Javascript, the dark theme toggle correctly sets the
data-theme
attribute.Not really sure where I could be going wrong..