Dark mode for your website

If you’re a Mac user, you’ve probably noticed that the latest version of Mac OS has a new feature called Dark Mode. All built-in apps support Dark Mode. Third-party apps can also choose to adopt it.

Mac OS Mojave Dark Mode
Dark Mode vs. Light Mode in Mac OS (source: Apple.com)

Dark Mode for your website

While some websites have a day/night switch, wouldn’t it be much nicer if you can automatically “detect” the user’s settings? Well, this could soon be possible, at least for WebKit browsers.

CSS media query for dark mode

There actually already is a media query that you can use in your CSS to change styling based on whether a user has “Dark Mode” enabled on their device:

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

Unfortunately, this won’t work in most browsers. However, Apple is adding a feature for Dark Mode to Safari. This can already be seen inĀ Safari Technology Preview, that gives you “an early look at upcoming web technologies” for MacOS and iOS.

Safari Technology Review icon in the Dock on Mac OS Mojave
Safari Technology Review

A screenshot of this website in dark mode

The CSS

In my stylesheet, I’ve added the “dark” media query and changed the background and text colors on my website accordingly:

@media (prefers-color-scheme: dark) {
	body {
		color: #fff; 
		background-color: #000;
	}
	.site-branding .site-title a {
		color: #fff;
	}
	.social-navigation ul.social-links-menu li a {
		color: #fff;
	}
	.social-navigation ul.social-links-menu li a:hover {
		color: #ccc;
	}
	.site-description {
		color: #ADADAD;
	}
	.main-navigation .main-menu > li > a, a, a:visited {
		color: #33BEFF;
	}
	.main-navigation .main-menu > li > a:hover, a:hover {
		color: #008BCC;
	}
}

Tip: When switching to a dark background, you’re probably going to need a lighter text color. I recommend using the WebAIM Color Contrast Checker to make sure all the colors still have an acceptable Contrast Ratio.

CSS vars

You can combine this media query with CSS variables to make your life a bit easier:

root: {
	--text-color: #000;
	--bg-color: #fff;
}

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

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

Leave a comment

Your email address will not be published. Required fields are marked *