Switching between light mode and dark mode with our test web page

How to detect the user’s theme in MacOS Mojave and use it to change the look of your website

Dark mode is in right now. It’s easier on your eyes in low light environments and it’s a refreshing change from the light metallic greys we’ve seen over the years. A distinguishing visual feature of MacOS Mojave is Dark Mode and app developers can take some steps to update their apps to take full advantage of this new feature, but what can we do as web developers to tap into this?

Some new media queries have the answer, you can check out the spec for prefers-color-scheme. The spec defines light, dark and no-preference options. The Safari team is on the case, so let’s test it out.

What can we create?

I put together a quick demo of what we can achieve with some basic styling rules and prefers-color-scheme.

Dark mode and light mode screenshots

How do I get started?

So how can we achieve this effect? Getting started is as easy as adding a media query to your CSS like so.

An example of how to use the prefers-color-scheme media query

You can target dark mode with:

@media (prefers-color-scheme: dark) { ... }

or target light mode with

@media (prefers-color-scheme: light) { ... }

In my example, we do a simple inversion of the colour pallet with something like:

body {
  background-color: whitesmoke;
}

.title {
  color: midnightblue;
}

@media (prefers-color-scheme: dark) {
  body {
    background-color: midnightblue;
  }

  .title {
    color: whitesmoke;
  }
}

Awesome let’s start using it!

Slow down there, as with most new and exciting CSS, not all browser vendors have implemented prefers-color-scheme yet, and it’s not even in Safari as of November but you can take a look using Safari Technology Preview.

Whether or not you’d like to use it, is up to you. I think it’s an interesting idea which could bring a dynamism to webpages without using JavaScript. It offers a chance to take into consideration the user’s preferences and use them to tailor your site without the user having to do anything. This makes for a consistent and delightful user experience.

At the moment, I can’t recommend rolling it out until more browsers get on board. I hope that support will grow, I see potential on mobile platforms if more thought is put into themes and accessibility that’s transferable to the web.


Check out the full example source code on GitHub.

Check out the website online (be sure to use the Safari Technology Preview on MacOS to see your theme impact the style).

Thanks for taking a look at something I think is pretty cool, please let me know if there is anything you’d like expanded upon or if you’d like to see more content of this nature. Happy coding!


Originally posted on Medium on November 17, 2018.