Support Mojave Dark Mode with Tailwind CSS
This article has been published a while ago.
If this is a technical article some information might be out of date. If something is terribly broken, let me know and I will update the article accordingly.
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.
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.