Today I Learned - Rocky Kev

TIL prefers-color-scheme automatically

POSTED ON:

TAGS:

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:

TIL the alternate keyword

If 'alternate' appears along with the stylesheet keyword, the linked file is an alternative stylesheet. It won’t be applied to the document, but it will be ready for when we need it.

TIL Logical Properties

For that sweet sweet Internationalization you want to avoid directional words like 'left', 'right', 'top', and 'bottom'.

TIL Using pseudo-classes in your querySelector!

let notTuna = document.querySelectorAll('.sandwich:not(.tuna)')