Dark mode detection in CSS

Updated September 3, 2020

Recently dark versions of operating systems and websites have become more popular, as they tend to put less strain on the eye at night. Recently both MacOS Mojave and Android 9 have added Dark Mode functionality, making the systems’ normally bright bars and backgrounds much darker. However, this is not much use if most websites you visit are still bright and harsh on the eyes. This is where the new CSS media selector prefers-color-scheme comes in. It lets you change your site’s styles based on the user’s OS-level preference for either light or dark styles.

prefers-color-scheme

Media queries are already widely used across the web for changing styles based on the size of the screen, such as different styling for desktop and mobile. To determine whether the user would like a light or dark mode, you can simply use the new prefers-color-scheme.

This CSS styles a page which has a white background and black text by default, but changes to black text on a white background if the user’s OS is set to dark mode.

body {
  background-color: #fff;
  color: #000;
}

@media(prefers-color-scheme: dark) {
  body {
    background-color: #000;
    color: #fff;
  }
}

If your site is dark mode by default and you want it to be light if the user prefers that, then the process is very similar.

body {
  background-color: #000;
  color: #fff;
}

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

Support

The latest versions of Chrome, Firefox and Safari all support prefers-color-scheme. Your preference for light or dark mode is taken from the operating system, and typically can’t be set at the browser level.

Most OSes now support dark mode, but there are still some that don’t. If you want to test prefers-color-scheme on a system like this, Firefox has a hidden config option for changing your preferred colour scheme to dark mode. Open about:config, and add a new Number value called ui.systemUsesDarkTheme. Choose a value of 1 to prefer dark mode, or 0 for light.

Demo

NewInWeb already implements prefers-color-scheme! Try changing your OS’s settings to prefer dark mode and reload the page. You can also try it in Firefox on any platform by changing the config as mentioned above.

Other recent posts: