How to perform arithmetic operations in CSS?

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".


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.


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.

Tags:

Css