47

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 want to give border on these divs. I want to write my rule like this.

#container {
    width: 50% - 1px; // I know this does not work.
}

Why do browsers not support such arithmetic operations in CSS ?

And, How can I get this to work ?

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 2
    “Why” questions are generally non-constructive. You should have presented your use case as a technical question (and written the title accordingly) calling for solutions, instead of “Just want to know why ?”. – Jukka K. Korpela Apr 23 '13 at 05:05
  • 1
    Thanks @JukkaK.Korpela Will take care from next time. – Sachin Jain Apr 23 '13 at 05:44

3 Answers3

71

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.

Adrift
  • 58,167
  • 12
  • 92
  • 90
  • 2
    @blunderboy For browser prefixes, see the answer: http://stackoverflow.com/questions/2434602/css-setting-width-height-as-percentage-minus-pixels#answer-14101451 – Ian Apr 23 '13 at 04:28
  • 2
    `calc` is [poorly supported in mobile browsers](http://caniuse.com/#search=calc), IE8, Safari <6, and Opera. Try using `box-sizing: border-box` instead. – Ross Allen Apr 23 '13 at 04:35
10

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

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
1

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.

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
interface
  • 21
  • 1