I have:
body { background: white; }
To display dark mode, I use .dark class:
.dark body { background: black; }
And to detect if user has their OS set to use dark theme, we have prefers-color-scheme:
@media (prefers-color-scheme: dark) {
body { background: black; }
}
And then we have the idea of DRY (Don’t Repeat Yourself) programming. Can we define dark mode without repeating CSS properties declarations, and in the process, allow users to switch between the color modes via JS?
With the above example, the .dark class and the media query are copies of each other.
What I've done so far
Skipped prefers-color-scheme in CSS and used:
body { background: white; }
.dark body { background: black; }
Then via JS, detect their settings and adjust the
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.getElementsByTagName('html')[0].classList.add('dark');
}
The problem with this approach is it doesn't use prefers-color-scheme in CSS.
While I can add:
@media (prefers-color-scheme: dark) {
body { background: black; }
}
It won't let me toggle the color schemes via JS because I can't cancel prefers-color-scheme: dark for a user who has dark set in their OS preferences.
What is the 2022 way of solving this?