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

Local Storage vs Cookies (The storage showdown)

javascript


Local site storage can open up a ton of possibilities in web design and breath new life into an otherwise static web page. Whether you want to do something simple like "show a welcome message only once", or something more complex.

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.

Five practical .htaccess tricks

apache - php


Apache's '.htaccess' has some very powerful tools that you can use with minimal effort to enhance the user experience and even performance, of your website.