Dark Mode on the Web

Using the prefers-color-scheme media selector

I recently rewrote most of this website (more on that soon!) and it’s now much easier to work on. Last week, I shipped a feature that I really like: dark mode using the new prefers-color-scheme media query. If you have dark mode enabled in your OS and a reasonably new browser, reillywood.com now shows you a dark UI using the Solarized colour scheme:

This is really easy to enable, and I hope more sites start using it soon. Under the hood, it’s just a straightforward media query in CSS:

@media (prefers-color-scheme: dark) {
    // Dark style rules go here
}

I borrowed a trick from Mark Otto where I dim images slightly in dark mode:

@media (prefers-color-scheme: dark) {
  img {
    opacity: 0.75;
    transition: opacity 0.5s ease-in-out;
  }
  img:hover {
    opacity: 1;
  }
}

Dark mode in Tailwind

Integrating it with Tailwind CSS was pleasantly simple. I added a custom dark media query in my Tailwind config like so:

extend:{
  screens:{
    'dark': {'raw':'(prefers-color-scheme: dark)'}
  }
}

And once that’s in place, I use it with a dark: prefix on my Tailwind classes:

// This sets a white background normally, and a black background in dark mode
<div class="bg-white dark:bg-black">
...

Browser support

For detailed information on browser support for prefers-color-scheme, caniuse.com is the place to go. It’s supported in the latest versions of Safari, Firefox, and Chrome, but it is on the bleeding-edge – Firefox and Chrome only shipped support for it last month, and dark mode itself is only supported in recent versions of macOS+Windows.

Still, it’s a nice progressive enhancement – any browser that doesn’t support it will just render the “regular” website styling. You can start using prefers-color-scheme now, even if most of your audience is stuck on older browsers.

headshot

Cities & Code

Top Categories

View all categories