I get 2 different output for the code below. It should give the same output since default value should be taken by the css variable. Below is the code where I commented passing span
a value, since it has a default value in the var declaration . Uncommenting the value assignment line give different output. Looking for a explanation of what is happening.
Here is the code pen with commented code - https://codepen.io/skandasoft/pen/MWjoMZe
and here is with uncommented - https://codepen.io/skandasoft/pen/VwKWJqd
Bootstrappy Grid with CSS Variables!<body>
<div class="grid">
<div class="item">1</div>
<div class="item" style="--span: 7">
<div class="grid" style="--cols: 2">
<div class="item">1</div>
<div class="item">2</div>
</div>
</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<style>
.grid {
display: grid;
gap: 10px;
grid-template-columns: repeat(var(--cols, 10), minmax(0, 1fr));
}
.item {
/* --span: 1; */
grid-column: span var(--span, 1); /**-span has a default value of 1 **/
background-color: yellow;
padding:10px;
}
</style>
</body>
Custom properties inherit.
From the spec:
Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules, ...
This means that if no value is set for a custom property on a given element, the value of its parent is used.
In this case, the parent element defines the custom property: --span
:
<div class="item" style="--span: 7">
So the value of the --span property will be 7 on all the children - unless a different value is explicitly defined on a child.
Now the difference between the two versions of the code is clear.
In the commented version, var(--span, 1)
in the .item class evaluates to 7 due to inheritance
Since there are only 2 columns in the grid, each item spans the full grid width
In the uncommented version (with --span: 1
; defined in the .item class), var(--span, 1)
in the .item class evaluates to 1 - because it is explicitly defined on the child.
Fallback values are only used as the substitution value when a given custom property is invalid / not defined
In this case, the second item in the outer grid defines the --span custom property with value 7 and it is available to all its child elements.