
Why You Should Be Excited About Native CSS Variables
Why You Should Be Excited About Native CSS Variables êŽë š
With CSS Variables now being under development for Edge (the last of the modern browsers to not support it yet) itâs time to dig up this brilliant post on CSS Variables. If youâre under the impression that CSS Variables offer nothing new when compared to Preprocessor variables, then this post is a must-read for you:
CSS preprocessors are fantastic tools, but their variables are static and lexically scoped. Native CSS variables, on the other hand, are an entirely different kind of variable: theyâre dynamic, and theyâre scoped to the DOM. In fact, I think itâs confusing to call them variables at all. Theyâre actually CSS properties, which gives them an entirely different set of capabilities and allows them to solve an entirely different set of problems.
The article first goes into detail on Preprocessor Variables and then switches over to CSS Variables, highlighting the differences and use cases where Preprocessor Variables fall short.
Say you want to style a button differenlty when it appears inside a header. Easy-peasy with CSS Variables:
.Button {
background: var(--Button-backgroundColor, #eee);
border: 1px solid var(--Button-borderColor, #333);
color: var(--Button-color, #333);
/* ... */
}
.Header {
--Button-backgroundColor: purple;
--Button-borderColor: transparent;
--Button-color: white;
}
Not entirely familiar with CSS Variables? CSS Variables: var(âsubtitle); is a good video/presentation to get you started.