Home → The Classics → Farai'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.
I’ll elaborate on this at some point but for now here’s a rough outline on how it works:
- I set two attributes on the
<html>
element,data-color-scheme
anddata-gamut
, both set to auto by default. - 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.
- 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.
- 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.