The problem is that this doesn't let the user toggle dark mode on/off. If you want the user to be able to toggle dark mode on your site without changing their Operating System preferences, then you'll need to implement your dark theme as a class (eg. body.theme-dark) since there's no way to dynamically set the media query. const darkMode = window.matchMedia('(prefers-color-scheme: dark)') if (darkMode) { document.bod…
If we want to support dark mode now we have to support four different options. Writing that with a combination of classes and media queries is going to be a nightmare:
.default-theme h2 { background: white; color: black }
.inverted-theme h2 { background: black; color: white }
@media (prefers-color-scheme: dark) {
.default-theme h2 { background: black; color: white }
.inverted-theme h2 { background: white; color: black }
}
Your trick might make this a little more palatable.