Implementing dark mode with prefers-color-scheme
Adding a dark mode to your website is quick and easy with CSS and the prefers-color-scheme media feature.
I've just added dark mode support to my site and wanted to do a quick post to document it. As a first pass, using prefers-color-scheme
is a really simple way to present visitors with a version of your site that is more aligned with their own viewing preferences.
I may later add a toggle option to allow visitors to switch between light and dark modes. But that's more work for what is essentially a nice-to-have. A visitor who prefers dark mode is unlikely to want to switch to the light version, and vice versa.
Which version are you seeing?
Well, the nice thing about prefers-color-scheme
is that it's a user preference set at operating system level. Some browsers, like Firefox, also let you choose between a light and dark theme that will override the operating system preference.
So, if your operating system or browser is set to use a light theme, you'll be seeing this site with a white background and black text. If you've chosen a dark theme instead, my site will have a black background with white text.
Here's the code
I'm using CSS variables for my colours, so here's a simplified version showing how it works:
:root {
--colorBackground: white;
@media (prefers-color-scheme: dark) {
--colorBackground: black;
}
}
The media feature prefers-color-scheme
is available in all modern browsers. Check out MDN web docs for more information.