Dark mode detection in CSS

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

Right now this is supported in Safari 12.1, and will soon be supported in Firefox 67. Your preference for light or dark mode is taken from the OS, so right now only on MacOS Mojave for Safari, or Android 9 for Firefox. In the future I expect that browsers may allow this to be configured in their menus.

Firefox 67 has a hidden config option for changing your preferred colour scheme to dark mode if you want to try it out on a system which doesn’t have a dark mode. Open about:config add a new integer value called ui.systemUsesDarkTheme. Choose a value of 1 to prefer dark mode, or 0 for light.

Demo

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

Other recent posts: