I’ll always share a simple solution because simple is almost always the best option. Theme preferences and toggles are one of those things that can be super over-engineered, so it’s great Christopher has come through with a simple solution for the former.
It’s something that’s still at the forefront of my mind since we’ve redesigned this site. We apply the theme in a very similar fashion but hot drama, we don’t apply the dark mode with a media query. Instead, we use matchMedia
:
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
It means our theme configuration is a lot simpler and manageable or we’d end up with this:
@media (prefers-color-scheme: dark) {
--color-global-text: var(--color-light);
--color-global-bg: var(--color-dark;
}
[data-user-theme='dark'] {
--color-global-text: var(--color-light);
--color-global-bg: var(--color-dark;
}
Once you apply a whole web design like that, it suddenly becomes quite expensive tech debt. My dream scenario? Something like this:
@media (prefers-color-scheme: dark), [data-user-theme='dark'] {
--color-global-text: var(--color-light);
--color-global-bg: var(--color-dark;
}
Until then, progressive enhancement baby!