Variables and conditional statements were widely requested by users since at least 2010. The consortium published a specification that included wording for variables back in 2012 ... but not widely implemented until 2018-19. Since the implementation, variables are not well understood and not well used.
Everyone seems to lump all variables under the :root { declaration. That means the life of the variable is throughout the entire document. You can also specify variables more localized, for example putting it in a "nav {" declaration would mean the life span of that variable is only within a nav tag (and anything under it).
The scope of a variable isn't what I had in mind for this article. What I really wanted to discuss was default values for variables – especially downstream in the call for a variable.
If you are like most developers, you have multiple CSS files. I have one that creates all the variables, and then another that is the "core" and several others that are specific use CSS files. For example, I have a "forms.css" that only gets accessed if there is a <form tag in the data stream.
My variable calls have default values ... that is because I can never be absolutely certain that a specific variable was defined. Rather than have a dead variable call, I create the call with a default in mind. Here's how that looks:
margin-left: var(–mrgn-left, 1rem);
That means that margin-left should be equal to the value in variable "–mrgn-left" ... and if that variable does not exist, the value is then 1 rem.
Never end up with a dead margin-left value again.
There's also a little known implementation of variables. That is directly in the HTML stream itself. Over the past few months, I've been intensively looking at one particular CSS Framework. What I noticed was the overuse of repetitive class names for simply defining a new value just slightly smaller or larger than the previous. One example would be to create a <div as a spacer between two other elements ... often because they don't fit a particular rule set to create custom CSS. For example: <div style="min-height:7px;height:7px;"></div>. You could, for example, have a CSS rule that such as: ".div-h: 7pxl;" and use it as <div class="div-h"></div> ... but what if you wanted 6px? or 5px? create a whole bunch of class names?
Wouldn't it be easier if you could define the variable in the <div ?
How about: we have the CSS as ".div-h: var(–div-height, 7px);" and then call it in the html as: <div class="div-h"></div> ... that would give us the div spacer with 7px of space.
Now for 6px, all we do is <div class="div-h" style="–div-height: 6px;"></div> ... strange as it may seem, that works. That changed the variable –div-height to 6px ... and ONLY FOR THAT DIV.
Now you can have a default defined in the CSS file, and change it on the fly in the HTML.
Enjoy!