How to perform arithmetic operations in CSS?

后端 未结 3 458
情话喂你
情话喂你 2020-12-25 11:30

I want to know how can I achieve an arithmetic operation in CSS.

For example: I want to align two divs side by side each having width of 50% and I w

相关标签:
3条回答
  • 2020-12-25 12:01

    It is possible with a CSS precompiler. LESS ans Sass are very popular. You can write it just the way you did it in the example above.

    http://www.lesscss.org/

    LESS is more easy to handle when you are a designer. For programmers and Ruby (on Rails) developers Sass maybe the better choice.

    0 讨论(0)
  • 2020-12-25 12:07

    Use box-sizing: border-box; on your <div> to make borders part of the width calculation. The default value for box-sizing is content-box, which does not include padding or border in the width attribute.

    #container {
      border: 1px solid black;
      -moz-box-sizing: border-box;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      width: 50%;
    }
    

    Paul Irish comments on the use of calc() and suggests using border-box because it better matches our mental model of "width".

    0 讨论(0)
  • 2020-12-25 12:17

    It already exists; You can use the CSS3 calc() notation:

    div {
        background: olive;
        height: 200px;
        width: 200px;
    }
    
    div > div {
        background: azure;
        height: calc(100% - 10px);
        width: 100px;
    }
    

    http://jsfiddle.net/NejMF/

    Note: It's only supported in modern browsers (IE9+) and has only recently been adopted by mobile browsers.

    0 讨论(0)
提交回复
热议问题