Simple dark mode with CSS filters
As a big fan of macOS Mojave’s dark mode, I was excited to see a new media query for targetting this user preference land in a recent release of Safari Technology Preview.
I’ve seen others add support to their websites by redefining colour variables or properties – which is probably the way to go in most cases. But it occurred to me that since this blog (currently) contains no images or rich media, I can get a very cheap dark mode by inverting the whole document using the filter
property, like so:
@media (prefers-color-scheme: dark) {
html {
filter: invert(100%);
}
audio,
canvas,
embed,
iframe,
img,
object,
video,
svg {
filter: invert(100%);
}
}
To see for yourself, open up this page in the latest Safari Technology Preview.
For good measure, I’ve also included a rule set to invert the images, videos, and other replaced elements back to normal, so that these don’t get inadvertently affected should I include them in future. This idea is borrowed from Are.na’s stylesheet, where they scope their dark mode styles to an .is-inverted
class (try it out on their site by using the keyboard shortcut Ctrl + Shift + i).