Using CSS dark mode based on OS-settings with fallback

The prefers-color-scheme in the editors draft Media Queries Level 5 can be used to detect if the visitor to a webpage has instructed their device to prefer a dark or light color scheme. You can then use their preference to style your CSS. For example:

@media (prefers-color-scheme: dark) {
	/* styles for dark color scheme here, e.g. */
	body {
		background-color: black;
		color: white;
	}
}

If the device does not yet support the prefers-color-scheme media feature (for example, it is not yet supported in the current extended support release of Firefox), one possible fallback is using classes like light-mode or dark-mode on the html element. Radio buttons with a little bit of JavaScript can be used to toggle between the two modes.

The fallback mechanism requires a bit of repetition in the CSS. For instance:

/* Set dark-mode colors by default */
html {
	background-color: black;
	color: whitesmoke;
}

pre {
	background-color: #0f0f0f;
	box-shadow: 2px 2px 0px #171717;
}

/* If the user's system indicates light mode, use light color scheme */
@media(prefers-color-scheme: light) {
	html {
		background-color: whitesmoke;
		color: #181818;
	}

	pre {
		background-color: ghostwhite;
		box-shadow: 2px 2px 0px #e6e6e6;
	}
}

/* If the user set light mode, use light color scheme */
html.light-mode {
	background-color: whitesmoke;
	color: #181818;
}

.light-mode pre {
	background-color: ghostwhite;
	box-shadow: 2px 2px 0px #e6e6e6;
}

/* If the user set dark mode, use dark color scheme */
html.dark-mode {
	background-color: black;
	color: whitesmoke;
}

.dark-mode pre {
	background-color: #0f0f0f;
	box-shadow: 2px 2px 0px #171717;
}

For this website, I took the approach of having a dark mode by default (saving a little bit of power, to help save the planet 🌍) and added explicit styles for a light-mode version of the website. The light-mode version of the website can be set either by detecting system settings or that the user set this setting with the color scheme picker on this website. The user may also choose to pick the dark-mode settting in which case, even if their system settings indicate a preference for light-mode, the dark-mode will still be used.

Leave a Reply

Your email address will not be published.

Color scheme: