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

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.

How to center things with CSS

html - css


Being able to center text, divs and images is one of the most important things that you can utilize to create clean and modern websites.

Immersive Parallax scrolling effect

javascript - css - html


You might have noticed while moving along in a car or train, how far away objects seem to move across your vision slower than those closer to your eyes. This effect is known as parallax and its a fundamental aspect of vision which can often go unnoticed.