Dark Mode CSS with the prefers-color-scheme media query

December 04, 2019

prefers-color-scheme is a new-ish CSS media query lets developers define styles tailored to a visitor’s color scheme system setting.

@media (prefers-color-scheme: light|dark|no-preference) { ... }

By default, this website has a white background with mostly black text. If visitor has their operating system’s colour scheme set to Dark, a few line of CSS is all that’s needed to make the website fall in line.

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

Browser Support

As of December 2019 browser support is already pretty good with added in iOS Safari 13.1 and Chrome 76.

Resources


Duncan McDougall is freelance web developer from Annan, Scotland.
LinkedIn GitHub Twitter