Dark Mode

Adding a dark mode feature to this website was a high in my TODO list from the beginning. Informed and inspired by a post by Derek Kedziora1, I set out to save your eyeballs from the blinding white lights. But it had to be simple; no JavaScript, no toggle buttons and just one CSS stylesheet.

My solution uses a the CSS prefers-color-scheme media query. Supported by most browsers2, this query has three values:

  • light
  • dark
  • no-preference

I then combined the media query with CSS variables. Here’s a look at my code to see how I implemented it:

@media (prefers-color-scheme: light) {
  --a-link-color: #00E;
  --a-visited-color: #551A8B;
  --background-color: #fafafa;
  --body-color: #212121;
  --letter-spacing: 0}
@media (prefers-color-scheme: dark) {
  --a-link-color: #4D4DF3;
  --a-visited-color: #885FAE;
  --background-color: #212121;
  --body-color: #fafafa;
  --letter-spacing: .061em}

You’ll notice there’s a bonus variable to loosen letter spacing in dark mode. This helps with legibilty of (almost) white text against a (not quite) black background.

You can see my live CSS here.