Getting Started with CSS Dark Mode is Easy

• ~400 words • 2 minute read

"Dark Mode" has taken the modern OS UI by storm over the past few years. Many apps have made this an option, but now users can implement a system-wide setting. The preference gets communicated to the apps and they can react accordingly.

Soon you'll be able to detect this setting in your websites by using the prefers-color-scheme media query feature in your CSS. In fact, if you're using Safari 12+ on macOS you already can!

Unfortunately that's also the only place it's working, at the time of this writing, but that's probably likely to change over the course of 2019. Currently it's in-development for Chrome and Firefox. With Microsoft Edge switching to Chromium it seems likely to me we'll see it adopted there as well, sooner than later, though there's no telling for sure.

Using the new feature is very straightforward if you're used to using media queries.

Here's an example:

/* Show dark text on a white background */
body {
  background:#fff;
  color:#0B2429;
}

/* If the user has dark-mode enabled make
the text white and the background darker */
@media (prefers-color-scheme: dark) {
  body {
    background:#0B2429;
    color:#fff;
  }
}

The documentation and examples at MDN illustrate this well and has an interactive examples as well. That's really it!

Conversely, setup a query to detect if the user has a preference set for light mode and respond accordingly:

/* Show white text on a dark background, as a default */
body {
  background:#0B2429;
  color:#fff;
}

/* If the user has light-mode enabled make
the text dark and the background white */
@media (prefers-color-scheme: light) {
  body {
    background:#fff;
    color:#0B2429;
  }
}

That's really all there is to it!

This is one of the more interesting CSS spec items to come down the pipeline to me not so much for what it enables but because Apple pushed it out before all of the other players, but only desktop! I really can't remember the last time a feature arrived on Safari for macOS before literally everything else.

I feel like dark mode is a little gimmicky, but recognize it might genuinely help some people with eyestrain. Sometimes I can even talk myself into that when I stay up too late staring at my screen. Even so, I feel like this makes more sense as a system-wide operating system feature to enforce and not something the website should be handling.

Far less gimmicky to me is the prefers-reduced-motion CSS media feature. If your website employs a lot of animations and transitions you can check for this feature and tone things down. It's also much more widely supported.