After delving into the world of CSS Custom Properties back in late 2017, I have finally grasped their true essence and the importance of the var()
function...
Contrary to common belief, they are not simply variables that directly represent CSS values.
CSS Custom Properties are exactly what their name suggests - they are essentially new CSS properties that do not have assigned values initially.
In the realm of CSS, an example of a variable truly representing a value is seen with the currentColor
property.
An instance showcasing this is:
.my-div {
border: 1px dashed currentColor;
}
Unlike variables like currentColor
, CSS Custom Properties serve as unique, named, null-value-properties...
...and these specially crafted properties can be reused just like standard properties such as width
, height
, and color
, with the flexibility to set and reset values in different contexts.
For example:
/* My custom property is --my-custom-width but I want this
property to hold different values in different contexts */
.left-two-thirds-of-page {
--my-custom-width: 120px;
}
.right-third-of-page {
--my-custom-width: 60px;
}
.my-div {
width: var(--my-custom-width);
}
This highlights why the var()
function plays a crucial role - it doesn't merely provide "the custom property", but rather retrieves the current value associated with the custom property and presents that value.
Additonal Reflections:
In retrospect, one might ponder whether the concept of name-value relationship would have been clearer if CSS Custom Properties were labeled as:
CSS Custom Property Names
and referred to their corresponding function as:
value()
thus leading to syntax like:
value(--my-custom-property-name)
Extending this idea, we could potentially utilize the value()
function (or var()
function) not only on custom properties but on any property.
For instance:
width: value(height);