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;
}
}