More and more operating systems are making dark mode a core feature of their user interfaces. Mac OS and Pop Os’s Gnome implementation are some good examples. Although enabling dark mode changes the styling of most native desktop windows and apps, it does very little for websites viewed inside various browsers. All hope is not lost however. Developers have the option to craft a different look depending on which color scheme is enabled. This is done via a media query called prefers-colors-scheme: dark and prefers-color-scheme:light. I’ll use this website’s implementation as an example.

Just as you would set media queries for different screen sizes, setting preferred color schemes for your website is done through you css files. For this website, I use a solarized dark background color when dark mode is enabled and use a plain white background color when light mode is enabled. Here is a copy of the css code.

:root {
    --color-background: #fff;
    --color-heading: #1f1f1f;
    --color-blue: #1a6aa7;
    --color-text: #1f1f1f;
    --color-subtle: rgba(0,0,0,0.8);
}

body {
    background: var(--color-background);
    color: var(--color-text);
}

@media(prefers-color-scheme: dark) {
    :root {
        --color-background: #002B36;
        --color-heading: #f1f1f1;
        --color-blue: #f1f1f1;
        --color-subtle: rgba(255,255,255,0.7);
        --color-text: #f1f1f1;
    }
}

Using CSS variables here is helpful so as to remain true to the DRY(Don’t Repeat Yourself) principle. As shown in the code, when dark mode is enabled, the media query changes our color declarations to fit our preferred colors that are suitable to the selected theme.

To test this (provided that your OS supports dark mode), switch between light and dark mode on your phone or computer.

In a way, this makes the traditional javascript implementation of changing color mode on websites obsolete. I find this approach a lot more adaptive and consistent with system UI. Hopefully this helped. Cheers.