Adding a Dark Mode to your Website

Posted on September 26, 2019
Updated October 3, 2019

With iOS 13 out and many prowling the net in darkmode, you may not want to shine a spotlight into their face should they happen upon your #fff body. It will very soon be an affront to do so as people expect dark backgrounds at night (even though I believe dark/light is an intermediary step between more complex ambient lighting compatibility, for which we as designers will rely much more on devices and host software).

Apple have a developer’s video explaining this process succinctly, but I thought it might be good to summarize the brief and easy process here. It also works in other browsers and is triggered by Window’s dark mode as well, although it awaiting specification.

1. Declare your support:

:root {
	color-scheme: dark light;
}

This will work with default web styling: undelclared background and text colours will switch between black and white. But what if you need to specify such colors? They won’t change automatially, but…

2. Setup and declare default for CSS variables

:root {
	--main-background: #fff;
	--main-text: #000;
}

Now you insert these into your stylesheet so that they will be loaded by default.

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

3. Change variables with a media query

But how do you know if someone is running dark mode? Media queries can handle this.

@media (prefers-color-scheme: dark) {
:root {
		--main-background: #000;
		--main-text: #fff;
	}
}

You can setup whatever variables you like and re-declare them in the dark mode media query.

The original video goes into mode depth of course, you should give it a watch if you want to support Dark Mode further.