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. Is there a way to define dark mode without repeating CSS properties declarations?
With the above example, the dark class and the media query are copies of each other.
CodePudding user response:
You can keep advantage of the CSS media query without actually using it in the CSS itself by using JS.
For example, taking your .dark class from your code, you could use a MediaQueryList object:
const darkMode = window.matchMedia("(prefers-color-scheme: dark)");
And set up a toggle for the class list of the document:
// Initial setting
document.documentElement.classList.toggle("dark", darkMode.matches);
// Listener to changes
darkMode.addListener((event) =>
document.documentElement.classList.toggle("dark", event.matches));
In that way you can focus in your CSS files on just defining the classes under the .dark class and you won't need to define it twice by using the media query. Also, doing it in that way you can setup settings for the user which would override the default OS Preference in case you want (for example saving it in a localStore, etc...)
CodePudding user response:
If you want to do this with css, you can try the following method
:root {
--body-background-color: white;
}
@media (prefers-color-scheme: dark) {
:root {
--body-background-color: black;
}
}
body {
background-color: var(--body-background-color);
}
CodePudding user response:
You could achieve that by reversing the logic.
body { background: black; }
@media (prefers-color-scheme: light) {
:root:not(.dark) body { background: white; }
}
