Search code examples
csscss-variablescss-calc

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?


Solution

  • 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>