Search code examples
cssvarcalc

I want to perform calculation on a variable in CSS. Is there a way to do this WHITHOUT preprocessors or JavaScript? [ACCEPTED]


I want to do something like this. I want to make use of a single varible for multiple elements that have different values for the same property.

like this v v v

:root {
  --brd_rad: 2rem;
}

#something {
  border-radius: var(--brd_rad);
}

#other-thing {
  border-radius: calc(var(--brd_rad) + 1);  /*obviously this doesn't work */
}

Solution

  • You need a unit in the value you're adding in the calc. Is it meant to be 1px or 1rem or 1%?

    :root {
      --brd_rad: 2rem;
    }
    
    #something {
      border-radius: var(--brd_rad);
      border:1px solid blue;
      height:100px;
    }
    
    #other-thing {
      border:1px solid red;
      height:100px;
      border-radius: calc(var(--brd_rad) + 1rem); 
    }
    <div id="other-thing"></div>
    <div id="something"></div>