csscss-variables

strange issue with css variables and abs and clamp css functions


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:

enter image description here

jsfiddle

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)?


Solution

  • As of now abs() is only supported by Firefox and Safari. Change abs(x) to max(x, 0 - x)

    .grid>*:nth-child(2n) {
      border-right-width: calc((1 - max(clamp(-1, var(--columns, 1) - 2, 1),
         0 - clamp(-1, var(--columns, 1) - 2, 1))) * 5px);
    }