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 {

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 {

Other Tutorials

View All

How to use jQuery's ajax to load dynamic content

javascript - php

Providing dynamically loaded content instead of loading a whole new page can go a long way in terms of improving the experience your users have on your website.

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.

Handy Python tricks for beginners


When first starting out in a language like Python, things tend to move a bit slow until you learn how to use the built-in functions and operators which exist to speed up the development process. So this tutorial will try to mitigate that problem.