HomeThe ClassicsFarai's Codelab

I’ve Added A Theme Switcher (The Basis For One Anyway)

Published: Updated:

I didn’t make this from scratch as all I did was move it in from a previous version for my site. The switcher let’s you toggle dark mode as well as switch between sRGB and display-p3 colors used in Apple devices.

There isn’t much difference between sRGB and p3. That’s because I suck at colors and I insisted on using blues. sRGB and display-p3 have a similar number of blues so there aren’t any new blues you get there.

I’ll elaborate on this at some point but for now here’s a rough outline on how it works:

  1. I set two attributes on the <html> element, data-color-scheme and data-gamut, both set to auto by default.
  2. I set up my CSS with variables corresponding to regular/light mode and dark mode as well as sRGB and display-p3 color gamut. In addition to those, I make a rule corresponding to the html attributes so they override the media queries.
  3. In the site’s head, I read the set theme color (if set) and modify the aforementioned attributes. That way, users don’t notice it working.
  4. The theme switcher at the bottom of the page sets the preference to session storage.

It’s more complex than this, but I’ll elaborate over time.