This weekend, I wanted to explore how I can add dark mode to my website, for the benefit of the ~2 people who read my blog. I decided to keep it simple, and use the system-wide preference for the colour mode. I thought I might have to use arcane CSS and Javascript incantations to first query the system dark mode preference, and then set the colours accordingly, but the browser vendors have made it so much simpler and easy to use.
Enough Talk! Show me the code
Here's all the code required to add dark mode to any website (with a few caveats I'll explain later in this post):
<meta name="color-scheme" content="dark light">
That's it! It requires no custom CSS, and is supported in all modern
browsers.
There's also a corresponding CSS property: color-scheme
, which works on
individual tags.
There's a major caveat though. If you've set custom colours anywhere on your
page, using the color
or background
CSS properties, this won't work for you.
It'll invert the colours only for the elements that have no explicit colour set.
Other approaches
If you make substantial use of custom colours in your web pages, you can use the
prefers-color-scheme
media query in your CSS to get a more fine-grained control of how your webpage
looks in different modes.
Here's an example:
@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}
I hope this helps!