calc() function inside another calc() in CSS

后端 未结 3 1951
野的像风
野的像风 2020-12-16 09:23

How do I use a CSS calc function inside another CSS calc function? According to this post it is possible but there is no example of that.

3条回答
  •  没有蜡笔的小新
    2020-12-16 09:50

    It is possible to use calc() inside another calc().

    An example:

    div{
      width: calc(100% - (1% + 30px));/* calc(1% + 30px) is nested inside calc()*/
    }
    div p{
      width: calc(100% - 30px);/*100% is total width of the div*/
    }
    

    Update on nested calc with css variables:

    .foo {
      --widthA: 100px;
      --widthB: calc(var(--widthA) / 2);
      --widthC: calc(var(--widthB) / 2);
      width: var(--widthC);
    }
    

    After all variables are expanded, widthC's value will be calc( calc( 100px / 2) / 2), then when it's assigned to .foo's width property, all inner calc()s (no matter how deeply nested) will be flattened to just parentheses, so the width property's value will be eventually calc( ( 100px / 2) / 2), i.e. 25px. In short: a calc() inside of a calc() is identical to just parentheses.

    So, the current spec as well proves this using parentheses inside calc() is nested calc.

    Learn more about css variables here.

提交回复
热议问题