Paul Miller avatar

I make projects which help developers to build awesome things. I solve problems related to online businesses at Hell Yeah. I adore travelling around the world, making great products and writing libertarian essays.

You can ping me on twitter or send me an email.

Using dark mode in CSS with MacOS Mojave

MacOS Mojave has been recently released with the Dark Mode option.

The option allows you to enable dark interface through all the system, which is very useful while working in the evenings and nights. Native apps are able to take advantage of the mode by following some interface guidelines.

What about web apps? Safari 12 that shipped with Mojave does not have a way to detect whether a user has a dark mode or not.

The good news is: Safari Tech Preview 68 supports Dark Mode! And Safari 12.1 might support it in a few months too. The CSS itself is very simple:

/* Text and background color for light mode */
body {
  color: #333;
}

/* Text and background color for dark mode */
@media (prefers-color-scheme: dark) {
  body {
    color: #ddd;
    background-color: #222;
  }
}

The prefers-color-scheme query supports three values: dark, light, and no-preference.

No polyfills are required, the media query code would be skipped if your browser doesn’t support it.

To use it in JS, window.matchMedia('(prefers-color-scheme: dark)') would do the trick.

For the demo, open this site in Safari Tech Preview with MacOS Dark Mode enabled. iOS and Chrome would probably also get a dark mode in the next major update.