Light/dark mode done fast

Back to list

There's a lot of documentation out there for Javascript light/dark mode toggles (a la styleswitcher), but you can do it with just CSS so it automatically changes based on a user's browser or device settings. You can do it even more easily if you use CSS variables. (Try switching your browser to a different display mode, then come back and look at this page.)

The gist of this is that if you define all of your colors via global variables (see W3 Schools for how to do that), you can copy them over and redefine them within your light/dark mode media query (whichever isn't your default color scheme) and have it done very quickly. On top of that, you can put anything you want into a CSS variable, so you can even do this for background images!

Code

If your default style is dark, change "dark" to "light" in the media query.

:root {
    --color1: #FFF;
    --color2: #000;
}

@media (prefers-color-scheme: dark) {
    --color1:#000;
    --color2:#FFF;
}