Support Mojave Dark Mode with Tailwind CSS

• 1 min read

Apple added a Dark Mode to macOS with the recent Mojave update. Apps which support Dark Mode look great, but when you switch to the web you almost always get blinded by all the websites which come in white. Luckily, there's a new media query which allows websites to adapt their CSS to the new Dark Mode. The latest Safari Technology Preview is currently the only browser supporting this media query.

Screenshots of stefanzweifel.dev: Light Mode and Dark Mode
Screenshots of stefanzweifel.dev: Light Mode and Dark Mode

I've written the CSS of my site with Tailwind CSS. Adding support for Dark Mode to Tailwind is super simple: Add the following configuration to the screens-object in your Tailwind configuration.

screens: {
  ...
  'dark-mode': {'raw': '(prefers-color-scheme: dark)'},
},

That's basically it. The next time you compile your CSS you will have access to CSS classes which will only be applied if the user prefers Dark Mode. Here's an example of the CSS written for the body:

<body class="bg-white dark-mode:bg-black">
    ...
</body>

It also works great if you use the @apply directive in your CSS file:

body,
html {
    @apply font-sans text-black antialiased;

    @screen dark-mode {
        @apply text-white;
    }
}

If you don't use Tailwind CSS you can achieve the same with the following code.

body,
html {
    color: black;
}

@media (prefers-color-scheme: dark) {
    body,
    html {
        color: white;
    }
}

As I mentioned, this media query is currently only supported in an unstable version of the desktop Safari browser, but will be available in stable Safari in the next months.