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

Using variables in CSS

css - javascript


When styling your web app, you've probably found yourself copying hex colour codes, margin parameters or other styles to several elements to achieve a consistent design across your app.

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.

Essential meta tags for the modern internet

html


Meta tags give you the power to customise how your site appears to the rest of the internet. They provide a simple and fast way for web crawlers and other applications to get information about a website.