Using CSS vars (including dynamic JS access)
Back to css
CSS now has variables! (Or "custom properties" as they are formally called.) I’ve wanted variables in CSS for decades and now we have them! Yay!
First, you define a variable in CSS. They’re scoped to the selector in which they’re defined, so to make "global" variables, you define them in the document root like so:
:root { --foo: #000; }
Then you use the variable wherever you would use that value in the stylesheet:
body { color: var(--foo); }
Looks weird, but it works!
(Here’s the aforementioned MDN article (mozilla.org). Also, today I learned that :root (mozilla.org) is a "CSS pseudo-class that matches the root element of a tree representing the document.")
Bonus: Dynamically change it with JavaScript
The value of the custom property (and thereby anything that uses that value) can be changed in JavaScript at "runtime" like so:
document.documentElement.style.setProperty('--foo', '#FFF');
Nice
This page was basically extracted from Day 28 of the Hiss log. To see the above stuff used to implent a full color scheme switcher in a text game editor, check that out.