Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Calc - always achieve '0' or '1'

I have CSS variable called --size which is set with javascript. Its value will be 0 or any whole number.

I wish to create a new CSS variable using the calc function. I want the value of this new variable to be either 0 or 1.

  • If --size = 0 then the new variable = 0
  • If --size > 0 then the new variable = 1

I can use the below code to achieve this:

--new: calc(var(--size)/(var--size))

But when --size = 0, this does not work.

Is there a way that I can adjust my calculation to achieve 0 or 1 dependent on the value of the variable?

like image 800
Adam Scot Avatar asked Nov 26 '25 12:11

Adam Scot


1 Answers

Use min()

--new: min(var(--size)*var(--size)*1000,1)

If size = 0 then the result is 0. If bigger than 0 or smaller than 0, multiplied with a big value (and itself) it will get bigger than 1 and will get clamped to 1

.box {
  --new: min(var(--size)*var(--size)*1000,1);
  
  height:50px;
  background:blue;
  margin:5px;
  
  border:calc(var(--new)*5px) solid red; /* either 5px here or 0 */
}
<div class="box" style="--size:2"></div>

<div class="box" style="--size:0"></div>

<div class="box" style="--size:200"></div>

<div class="box" style="--size:-200"></div>

<div class="box" style="--size:-.5"></div>

<div class="box" style="--size:.8"></div>
like image 175
Temani Afif Avatar answered Nov 30 '25 23:11

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!