Skip to content

Instantly share code, notes, and snippets.

@ivan
Last active August 11, 2023 23:04
Show Gist options
  • Save ivan/197e5d8bdd98d0aaf020d52475eb02fa to your computer and use it in GitHub Desktop.
Save ivan/197e5d8bdd98d0aaf020d52475eb02fa to your computer and use it in GitHub Desktop.
CSS light and dark mode without JavaScript requirement and with a class-based override on <html>
html {
background-color:
var(--LIGHT, #eee)
var(--DARK, #111);
color:
var(--LIGHT, #000)
var(--DARK, #ccc);
}
html {
--LIGHT: initial;
--DARK: ;
}
@media (prefers-color-scheme: dark) {
html {
--DARK: initial;
--LIGHT: ;
}
}
/* Override `prefers-color-scheme: dark` if class is present */
html.light-mode {
--LIGHT: initial;
--DARK: ;
}
html.dark-mode {
--DARK: initial;
--LIGHT: ;
}
@ivan
Copy link
Author

ivan commented Jul 27, 2023

In color: var(--LIGHT, #000) var(--DARK, #ccc);, when --LIGHT is invalid (set to initial) it falls back to #000, at the same time --DARK is valid (a whitespace) so that part just evaluates to a whitespace instead of #111.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment