Reputation: 21842
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 ?
Upvotes: 47
Views: 43349
Reputation: 44880
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".
Upvotes: 10
Reputation: 21
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.
LESS is more easy to handle when you are a designer. For programmers and Ruby (on Rails) developers Sass maybe the better choice.
Upvotes: 1
Reputation: 59779
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;
}
Note: It's only supported in modern browsers (IE9+) and has only recently been adopted by mobile browsers.
Upvotes: 72