CSS calc() - Multiplication and Division with unit-ed values

前端 未结 2 437
野性不改
野性不改 2020-12-09 15:12

Is it possible to use calc() to multiply or divide with unit-based values (like 100%, 5px, etc).

For example I was hoping to do something like this:

         


        
相关标签:
2条回答
  • 2020-12-09 15:37

    In CSS calc() division - the right side must be a <number> therefore unit based values cannot be used in division like this.

    Also note that in multiplication at least one of the arguments must be a number.

    The MDN has great documentation on this.

    If you'd like a better way to do calculations you can use a preprocessor (I like Sass). That link will take you to their guides (on that page there's a section about operators).

    0 讨论(0)
  • 2020-12-09 15:38

    For someone who is making a mistake like me, don't forget that you can't use sass variables in css calc function directly, for that you have to use sass calculation method

    $test: 10px;
    
    .testing{
        width: #{$test * 2};
    }
    

    or if still calc implementation is necessary

    $test: 10px;
    
    .testing{
      width: calc(50% + #{$test * 2});  // results in calc(50% - 20px)
    }
    
    0 讨论(0)
提交回复
热议问题