css dark-mode/light-mode - rethought

css dark-mode/light-mode - rethought

So, you read my last blog entry about "CSS, Dark-Mode and Custom Properties" and start to build for every website a light and a dark theme, to support your visitors. That's nice - and then you like your light theme more than the dark theme and your mobile phone switches between light and dark theme according to sun hours?
Or you don't care on your Windows desktop about the light/dark global theme, but you do want to use the opposite theme of this website you built?
Or you are proud of both themes and want every user to be able to switch between these themes, even if he does not know about light-mode or dark-mode settings?

In this post, we will give the user the power to choose between a dark and a light theme, but preserve the media-query magic, for those who don't care. At the end of this page, there is a gist with a working example.

the built-ins

With media queries you can meet the user preference:

@media (prefers-color-scheme: dark) {
  /* dark theme adjustments */
}

or if your colors are darkish by default:

@media (prefers-color-scheme: light) {
  /* light theme adjustments */
}

and if you use CSS custom properties the theming itself (overwriting custom properties) is not that big issue, but designing a light and a dark theme still will be.

the way around

You start your theming in a data-attribut'ish namespace on your html element. For example data-theme="light" and data-theme="dark". But don't forget to set one of these themes be your default, so send on initial request the data-attribute along, or just use one override. My advise is to deliver a basic theme which does not depend on the data-attribute, since we will alter that attribute with JavaScript and if a plattform goes wild and set the attribute value for some reason to undefined your user will be in trouble.

<!doctype html>
<html data-theme="light">
    <body>...</body>
</html>
:root {
  /* colors taken from here: https://color.adobe.com/de/Neutral-Blue-color-theme-10152035*/
  --body-background: #193441;
  --text-color: #FCFFF5;
  --another-color: #91AA9D;
}

html[data-theme="light"] {
  --body-background: #FCFFF5;
  --text-color: #3E606F;
  --another-color: #D1DBBD;
}

why html element?

We want to set the chosen theme, as soon as possible. In <head> context, the <body> element is not yet available. By manipulating the <html> element from the <head> element, the user will instantly get the theme he chosed, without a flash of the other theme.

the javascript bit

After crafting a light and a dark theme, you may want to let your user choose, which theme he want to use:

if (window.confirm('Hello, this website provides another theme for you, wanna try it?')) {
  document.documentElement.dataset.theme="light";
  window.localStorage.setItem("theme", "light");
} else {
  window.localStorage.setItem("theme", "dark");
}

On load put this JavaScript in your <head> if the user already chosen one theme, css rendering will directly use this setting:

<script>
    var theme = window.localStorage.getItem("theme");
    if (theme) {
        document.documentElement.dataset.theme = theme;
    }
</script>

Now, your user can choose which theme he'd like. If you switch between themes, you should also provide a "go back" button, like every operating system does when you fiddle on your screen settings ;-)

no more media query magic?

Right now we eliminated the media query goodness out of our website, but that's not the idea.

With window.matchMedia we can listen for changes and check media queries in our JavaScript (yeah!).

    var mqDark = window.matchMedia('(prefers-color-scheme: dark)');
    var mqLight = window.matchMedia('(prefers-color-scheme: light)');
    
    function checkTheme(event) {
        if (event.matches) {
            if (event.media.includes('dark')) {
                document.documentElement.dataset.theme = 'dark';
            }
            if (event.media.includes('light')) {
                document.documentElement.dataset.theme = 'light';
            }
        }
    }
    
    mqDark.addEventListener('change', checkTheme);
    mqLight.addEventListener('change', checkTheme);   
    

But the callbacks don't fire on initial execution, so we need to add another check to that:

    var theme = window.localStorage.getItem('theme');
    if (mqDark.matches && !theme) {
        // don't store in localStorage because it is not a user setting
        document.documentElement.dataset.theme = 'dark';
    }

    if (mqLight.matches && !theme) {
        // don't store in localStorage because it is not a user setting
        document.documentElement.dataset.theme = 'light';
    }

The theme check is our handbrake, so a user chosen theme (from the window.confirm dialog before) don't get overwritten.

the whole picture

In this gist, I put the whole working code.

Article Image from Osman Rana via unsplash and ghost ❤.

Show Comments