Creating a dark mode (for this tiny personal site) was way easier than I thought it was going to be. It had been a loose idea of mine for a long time, but it wasn’t nearly as bad as I expected, and I shouldn’t have put it off. All told, it took under an hour.
The key things I wanted dark mode to do were these:
CSS variables are essentially the answer to “make modes easily interchangeable”. For whatever reason, I mistakenly believed that CSS variables required a preprocessor like SASS or LESS; they don’t. The key is adding a
dark-mode class full of color variables to the
html element, and then switching between these classes. For example, I now have classes that look like these:
This required a slight refactor, mostly just searching for colors (a
#...... regex worked fine) and extracting them into light mode variables, then adding their dark mode equivalents. Now, when I manually added a
light-mode class to the
html element, I could see the modes switch before my eyes.
The answer to “don’t use a database” is “use
localStorage”. If someone has their mode saved in
localStorage, I use that to set the mode. However, I additionally wanted to respect people’s preferences upon the very first load of a page. For this, we can use
window.matchMedia("(prefers-color-scheme: light)").matches to find whether someone prefers a light color scheme, otherwise set it to be dark.
Finally, I wanted a toggle that would allow people to change the scheme they preferred on the fly (and save their preference in
Try it out!