Vary one part with variables
Set a variable for the part that changes, not the whole property.
Adam Wathan@adamwathanThis is the *coolest* part of CSS Variables to me! You can dynamically update just the part of a declaration you care about instead of redeclaring the whole thing ๐๐ป
Adam Wathan@adamwathan@drmzio The color variants are separated from the base styles, and they just set a handful of variables the base styles manage. So adding a new color is just creating another of of these, not wrangling a list of 70 classes.
The button is an invented example; character counts come from the strings it writes.
1 ยท Change one hue
Pick a hue or glow and watch what gets written.
Redeclare whole shadowBad
Nothing written yet
Set one variableGood
Nothing written yet
.btn {
--hue: 245;
--glow: 16px;
background: linear-gradient(hsl(var(--hue) 80% 42%), hsl(var(--hue) 80% 34%));
box-shadow:
0 1px 0 hsl(var(--hue) 90% 80% / .6) inset,
0 8px var(--glow) -6px hsl(var(--hue) 80% 50% / .7);
}
.btn.rose { --hue: 340; }
Why it matters, pros and cons
Why it matters
A variable holds the one piece that varies, so a variant sets a value and the base keeps the rest.
Pros
- A new color is one small rule, not another copy of every property.
- The base declaration stays the single place that defines the look.
- JavaScript can update one value and the whole declaration follows.
Cons
- Variables hide the final value, so devtools need one more step to read it.
- Too many variables turn the base styles into a puzzle to follow.
- A variant that changes the shape, not one part, still needs its own rules.