Dark Mode and CSS Media Queries

Dark mode is all the rage these days.

Windows has had one for a while, Apple have just released support with macOS Mojave and the latest version of Safari Technology Preview now supports adjusting your site’s CSS based on whether you’ve toggled dark mode on.

The media query in question is prefers-color-scheme: light | dark and is part of Media Queries Level 5, currently a draft spec. I’ve put it into use on this site to have a play around with; here’s the code I use to switch the colours with CSS variables.

:root {
  --background: #fafafa;
  --text: #212121;
  --brand: #fbe26d;
}

@media (prefers-color-scheme: dark) {
  :root {
    --background: #212121;
    --text: #fafafa;
  }
}

body {
  color: var(--text);
  background-color: var(--background);
}

I think the results are pretty great! See the video below…

You can give it a try yourself if you’re using macOS Mojave and the latest Safari Technology Preview, but I don’t imagine it will be long until other browser makers bring in developmental support. There’s a lot of potential here but as with everything it’s worth using in an appropriate, sparing way.