I am having trouble seeing why the following CSS code involving custom css variables fails to work as expected:
html
<ul class="grid">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
css
.grid > *:nth-child(2n) {
border-right-width: calc((1 - abs(clamp(-1, var(--columns, 1) - 2, 1))) * 5px);
}
.grid {
--column-gap: 10px;
--row-gap: 20px;
--columns: 5;
}
Output:
The problem is that every 2n
item has a right border width, when by calculation the border-right-width
should be zero (since --columns
has a value other than 2
and 1 - abs(clamp(-1, var(--columns, 1) - 2, 1))
should evaluate to 0
).
What am I missing? And how can the border-right-width
calculation activate only when --columns
takes the value of 2 and not otherwise (otherwise 0)?
2
Answers
To ensure that the border-right-width is only applied when –columns is exactly 2, you need to adjust your calculation. You can use a simpler check:
}
However, the equality check
(==)
is not supported in CSScalc()
. As a workaround, you could use JavaScript to dynamically add a class or inline style based on the value of--columns
.If you want a pure CSS solution, check below:
HTML:
CSS:
Here, you manually set the data-columns attribute in your HTML to match the
--columns
value. Then, you use this attribute in your CSS to selectively apply styles. This method requires updating the HTML whenever you change the--columns
value.As of now
abs()
is only supported by Firefox and Safari. Changeabs(x)
tomax(x, 0 - x)