dgl.cx

Switchable dark mode with 5 lines of JavaScript

In lyra's excellent, epic blog post "You no longer need JavaScript" there is a section (Lunalover) on how to make a switchable dark mode in only HTML + CSS.

The short version is you add some buttons (which you can style to not look like buttons), which then override the color-scheme as needed through :has() queries on the buttons' checked state:

:root {
  color-scheme: light dark;
  &:has(#theme-light:checked) {
    color-scheme: light;
  }
  &:has(#theme-dark:checked) {
    color-scheme: dark;
  }
}

She then goes on to say:

Pro tip! CSS can’t save the theme preference, but you can still do progressive enhancement. Make the themes work CSS-only, and then add the saving/loading of preference as an optional extra in JavaScript or server-side code.

So I thought I'd do exactly that. The icon at the top right of the banner of this site (scroll to the top to see it) will change the mode and save the perference to your browser's localStorage.

This works through some HTML to display the icons:

<span role="radiogroup">
  <label title="auto" id="theme-auto-label">
    <input type="radio" name="color-scheme" id="theme-auto" checked>✨
  </label>
  <label title="light" id="theme-light-label">
    <input type="radio" name="color-scheme" id="theme-light">☀️
  </label>
  <label id="theme-dark-label" title="dark">
    <input type="radio" name="color-scheme" id="theme-dark">☁️
  </label>
</span>

Some CSS to hide all but the next icon (i.e. the icon shows what clicking it will do):

header {
  @media (prefers-color-scheme: dark) {
    &:has(#theme-auto:checked) #theme-dark-label,
    &:has(#theme-light:checked) #theme-auto-label,
    &:has(#theme-dark:checked) #theme-light-label {
      display: none;
    }
  }

  /* ... 2 other sets of selectors for different media query + label combinations. */
}

That all works and is really only a minor modification of the original article, including essentially toggle buttons for the theme that is used, totally without JavaScript, but it doesn't save the state between pages.

That just needs a tiny piece of JavaScript:

for (const item of ["theme-auto", "theme-light", "theme-dark"])
  document.getElementById(item).addEventListener("change", () =>
    localStorage.setItem("theme", item));
let theme = localStorage.getItem("theme");
if (theme) document.getElementById(theme).click();

Basically save the state if the user changes it and when the page loads, "click" the relevent button if they saved the state. If the user visits multiple pages the JavaScript will be cached, so this basically happens right on load. If the user doesn't have the JavaScript cached it may result in a flash of colour. (This could obviously be avoided by inlining these few lines, but then I would have to adjust the CSP so I decided to live with this.)

One more hack was needed to fully implement dark mode, the GitHub icon at the bottom of each page didn't look good, so I changed the image via CSS, using object-position to hide the original image and override the background via CSS:

/* A lot of code just to get the github icon looking right... Has to be duplicated for different media queries. */
@media (prefers-color-scheme: dark) {
  body:not(:has(#theme-light:checked)) footer a[href="https://github.com/dgl"] img {
    object-position: -99999px 99999px;
    background-image: url('/static/github-white.png');
    background-size: contain;
    backdrop-filter: grayscale(1) opacity(.5);
    &:hover {
      backdrop-filter: opacity(1);
      transition: backdrop-filter 500ms;
    }
  }
}

All this is in the CSS and JavaScript resources for this site, feel free to use elsewhere (sorry the CSS is a bit disorganised, it has been evolved over many years...).