Building an Instant Theme Toggle With CSS Custom Properties
The classic problem with dark/light toggles on static sites is the "flash of wrong theme" β the page renders in the default color scheme for a split second before JavaScript catches up and applies the user's saved preference.
The fix: an inline script in <head>
Before any CSS or JS bundle loads, a tiny inline script reads localStorage.theme-pref and sets
data-theme on <html> synchronously:
<script>
var pref = localStorage.getItem("theme-pref") || "auto";
var resolved = pref === "auto"
? (matchMedia("(prefers-color-scheme: dark)").matches ? "night" : "day")
: pref;
document.documentElement.setAttribute("data-theme", resolved);
</script>
The CSS side
:root { /* day values, the light-first default */ }
:root[data-theme="night"] { /* dark overrides */ }
:root[data-theme="day"] { /* explicit light overrides */ }
Because everything is a custom property, toggling data-theme on the client is instant β no
network request, no rebuild, no flash. It's essentially the same trick GitHub and Discord use for
their own theme switches, just scoped to two skins named after the Tokyo Night variants.
π¬ Comments are not enabled on this demo site. Wire up Disqus, Utterances, or Giscus here.