CSS-Only Dark Theme

| tech

This website now respects the color scheme you selected in your operating system or browser. So if you'd prefer light text on dark background, check your settings.

The implementation is entirely in CSS and, to my surprise, took less than five minutes. Essentially, it's just the usual light default at the root level and a media query that detects the client's preferred color scheme and changes the defaults related to color if a dark theme is requested.

:root {
  color: black;
  background-color: white;
}

@media (prefers-color-scheme: dark) {
  :root {
    color: white;
    background-color: black;
  }
}

Instead of just setting the attributes, I actually create a few custom properties that I can access wherever convenient, but you get the gist. On my old website, I used Javascript to allow the user to toggle the theme, but I think the CSS solution is superior. You just set your preference in one place and get the right theme from the start, I, on the other hand, get rid of the Javascript snippet on each page.

I tested this setup on Firefox and it works just as expected: the Firefox default falls back to the setting of the OS, the browsers' light/dark themes overwrite the OS setting. Unfortunately, this doesn't seem to work with the GTK+ theme on Chrome. I suspect it's a Chrome-on-Linux issue, but if you experience the same problem on a different OS, take it as another reason to move away from Chrome. 😛