Sometimes there is a need to select between two values based on some condition in css styling. One can uses simple two classes or javascript two select right stiling. But thanks to css variables if statements can be done also in pure CSS.
To select between two values in pure CSS you can use folowing math trick
Pseudocod:
if( valueSel < th)
return valueA
else
return valueB
This statement can be converted to folowing pseudocod:
selector = (sign(valueSel-th)+1)/2
return valueA * (1-selector) + valueB * selector
Which can be expresed with help of css variables as:
CSS:
.some-class {
--valueSel: /* Some Value - predicate */;
--th: /* Some Treshold */;
--valueA: /* Result A */;
--valueB: /* Result B */;
--selector: calc(clamp(0,tan( clamp(-1,var(--valueSel) - th, 1) ),1));
--result: calc( var(--valueA) * (1 - var(--selector) ) + var(--valueB) * var(--selector) );
}
The selection can be extended to selecting colors via mix-color
You can see usage if this in Pure CSS radiational progress bar
https://codepen.io/owcakw/pen/KKEGvgZ
Top comments (0)