it beats a sharp stick in the eye

Adding a simple dark blog theme using CSS

December 22, 2020 — Gideon Mayhak

I've started using dark themes on some of the devices I use, including my phone, and I was struck by my blog's default black-on-white theme when viewed at night. I like the ligher theme as a default, but I wanted to accommodate folks (including myself) who prefer a less bright look.

Since I've gotten used to some sites automatically adjusting based on the device's theme settings, I figured I'd see if it would be easy enough to do the same for my blog. Here's my bare minimum attempt at implementing it using only Cascading Style Sheets (CSS).

Let there be dark

Since this blog is handily generated using bashblog and I really didn't want to go modifying the script, it was only worth it to me if I could do it in CSS. I was hoping to use a minimal number of additional lines, and I did not want to use JavaScript at all.

Here's my very sloppy solution that I added to the bottom of main.css:

@media (prefers-color-scheme: dark){
html{filter:invert(0.9) hue-rotate(200deg)}
img{filter:invert(1) hue-rotate(160deg)}

Bad formatting aside, the main points are prefers-color-scheme and the invert filter function. I'm only applying these changes if the user has specified the "dark" color scheme, and then I'm inverting everything 90% (so it's not completely white-on-black; I think it looks a little nicer this way). I also added hue-rotate so things like link colors aren't changed from blue to orange (again, I think it looks nicer).

Lastly, I have a separate img line to undo the inversion for images. However, because I'm not inverting 100% the first time and you can't invert more than 100%, I am only really bringing it back 90%. This means images will seem a little duller in dark mode, which might actually be a plus. Since hue-rotate is in degress, I am able to reverse that pretty much all the way by using 160deg. At least, I think that's how it works.

Feedback welcome

It may look okay to me, but I don't intend to be the primary audience of my own blog. If you use dark themes and see any issues with what I've done here, please let me know. You don't have to know anything about how it works, but I would also love actual suggestions on how to improve things.

"Won't the day of the LORD be darkness, and not light?
Even very dark, and no brightness in it?"

Amos 5:20, WMB

Tags: blog-info, how-to