Check User's Dark Mode Preferences Automatically in CSS and JavaScript

Use Case: Improve user experience

It's not just cool to have an option to toggle your site to dark- or light-mode, it's meangingful for the experience of users on your site or application.

There are a lot of different ways that you can set this up with CSS and JavaScript, but you can take this a step further by updating your CSS style's automatically based on the user's preferences.

How can we know this automatically?

MacOS and Windows 10 allow the users of their operating systems to choose to use their computers in either dark- or light-mode (typically light-mode by default). Browsers such as Chrome and Firefox automatically detect this from the OS for the style of their windows. They then emit the preference to CSS in the form of a media query called prefers-color-scheme - light or dark.

With CSS we can set a simple media query that sets styles depending on the mode, like this:

CSS

@media(prefers-color-scheme: dark) {
	body {
		background-color: black;
	}
	...
}

And in JavaScript we can check the contents of the windows matchMedia property:

JavaScript

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
	$('body').addClass('dark')
	...
}

We could also check both of the above for 'light' instead of 'dark'.

On this site, I check for your preferred setting and update the formatting of the pages accordingly. I also have a toggle button that you could click to override the mode in case you'd still like the option to choose!

Tweet me @tylerewillis

Or send me an email: