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.
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 in your page, using the color
or background
CSS properties, this won't work for you. It'll invert the colours only for elements which have no explicit colour set.
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 on 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!
Also published here.