Detecting system dark mode in CSS

26 Nov, 2019

The “dark mode” feature has been spreading to apps and websites far and wide recently. It brings a new and discrete look to your applications as well as offering some extra control to the user in terms of how they want to customise their experience.

If your planning on adding “Dark mode” to your website, you have a few choices to make in terms of how you want to implement the feature. The first of which is to add a toggle within your app to let the user switch between dark and light mode. A cookie or local storage variable could be used to maintain the state of the user’s dark/light mode preferences. Then using javascript, load separate styles if the local storage variable is set to dark. If you need help working with local storage variables, check out my article which covers both HTML5 local storage and cookies here.

An alternative and relatively new technique of implementing dark mode is to simply piggyback off of the user's device preferences using “prefers-color-scheme” in css. Used within css media queries, this attribute is set by the browser based on the current device color settings set by the user.

For example: Windows, Mac OS, Android, IOS, ect. All have some form of night/dark mode that can be enabled by the user. If dark mode is enabled on one of these platforms and the user is browsing on a supported browser View supported browsers here. then “prefers-color-scheme” will be set to dark, otherwise it will be set to light.

Detecting system dark mode in css is simple. Using familiar media queries, you can specify the styles you wish to be active in the different cases. The following code changes the page background to a dark grey and sets the text color to white.


@media screen and (prefers-color-scheme: dark) {
	body {
		background-color:#212121;
		color:#FFF;
	}
}
			

You may instead opt to include a dark mode by default and check for system light mode like this.


@media screen and (prefers-color-scheme: light) {
	body {
		background-color:#FFF;
		color:#000;
	}
}
			

Other Tutorials

View All

Responsive web design guide

css - html


In 2017 it was recorded that around 63% of all U.S web traffic is made up of mobile devices. It is becoming increasingly vital that websites adopt a responsive design to accommodate this rapidly growing portion of the market.

Building a custom chromecast web app

html - javascript


Chromecasts make streaming your favourite songs, games and movies easy. But if you're like me, you might be wondering what's going on behind the scenes when you cast an app, and how you can build your own.

Triggering vibrations from your website

javascript


Most common mobile browsers (excluding safari) allow you to trigger the device's vibration motor from your web application using the Vibration API. The Vibration API is provided to you by the mobile browser itself.