Ben Rabicoff

Using Dark Mode in CSS

With the recent release of MacOS Mojave, and a new 'Dark Mode' option, Apple has followed with release 68 of Safari Technology Preview.

In this release, the prefers-color-scheme media query support for styling dark mode content has been added. This media feature accepts three values: no-preference, light, and dark. You can read more in depth information in the W3C specification.

For this site, I've taken advantage of CSS variables to control all colors for the site under the :root CSS selector. Because of this, styling CSS for Dark Mode was a breeze.

I simply duplicated my CSS :root variables, and placed new values under the prefers-color-scheme media query. Now, if a user comes to the site with Dark Mode enabled on MacOS, the prefers-color-scheme media query takes precedence, and the associated colors are displayed.

:root {
    --color-body-bg: rgba(255,255,255,1);
    --color-body: rgba(68,68,68,1);
}

@media (prefers-color-scheme: dark) {
    :root {
        --color-body-bg: rgba(0,0,0,1);
        --color-body: rgba(255,255,255,.85);
    }
}

Before the release of this new media query, I had already coded a manual light/dark switcher on the site. Now I needed a way to disable this switcher if a user had Dark Mode enabled at the system level.

To do so, I wrote this piece of Javascript:

var interfaceBtn = document.querySelector('.interface-switch');
var pcs = window.matchMedia( "(prefers-color-scheme: dark)" );

if (pcs.matches) {
	interfaceBtn.style.display = 'none';
}

This simply looks to see if 'Dark Mode' is enabled via CSS, and hides the light/dark switcher on the site.