TIL prefers-color-scheme automatically
POSTED ON:
TAGS: css automation
Although I'm a pretty heavy user of Javascript, I do hate using JS for everything. If all you have is a hammer, then everything is a nail.
For swapping between light mode and dark mode, you don't need JS. (Although you WILL need JS to save preferences into session/local storage.)
Using the prefers-color-scheme
, that will automatically run the design code based on the user's preference.
@media (prefers-color-scheme: dark) {
.day.dark-scheme { background: #333; color: white; }
.night.dark-scheme { background: black; color: #ddd; }
}
@media (prefers-color-scheme: light) {
.day.light-scheme { background: white; color: #555; }
.night.light-scheme { background: #eee; color: black; }
}
But also giving them choice using a simple :checked
selector.
#darkModeCheckbox:checked {
body {
background: darkgrey;
color: whitesmoke;
}
}
MDN - prefers-color-scheme
5 things you don't need Javascript for
Related TILs
Tagged: css