Reputation: 785
I have a problem which I do not understand. If I use percentage in width, I would expect that elements calculate borders, margins or paddings within their size (in percentage). But in fact those values are added to their size which I asume is wrong. Is my expectation wrong? The bellow example shows the issue. The both "divs" "left" and "right" I expect to be in a single line. If I remove "border" it works as expected.
<!DOCTYPE html>
<html>
<head>
<style>
.center {
border: 1px solid black;
width: 100%;
overflow: auto;
}
.left {
border: 1px solid black;
width: 20%;
float: left;
}
.right {
border: 1px solid black;
width: 80%;
float: left;
}
</style>
</head>
<body>
<div class="center">
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
Upvotes: 2
Views: 12117
Reputation: 12848
In super modern browsers you can use calc() to fix this: calc(80% - 2px). And yes, it is normal. If you set the width to 100px and border to 150px what would happen then if border wasnt added?
Upvotes: 0
Reputation: 29433
What you can do to fix this issue is to use box-sizing. See http://jsfiddle.net/Marwelln/YYkxK/
box-sizing:border-box
Upvotes: 12
Reputation: 21888
Padding or Border always adds to an elements size, inside out.
Margin never adds to size but adds space outside the element.
Percentages or set values don't matter. The above is always true.
Reviewing the box model may help ---> HERE
Upvotes: 1
Reputation: 57346
When you use percentage as width (or height) values, these are the percentage of the width (or height) of the parent block element (containing block).
Upvotes: 0
Reputation: 21894
That's totally normal. It's not what you might expect at first, but CSS works that way.
Even without percentages:
#width {
width: 100px;
padding: 0 20px;
}
This #width div will occupy 140px. Works the same for percentages.
So you might need inner divs to achieve what you want.
<div class="left">
<div class="inner">
</div>
</div>
<div class="right">
<div class="inner">
</div>
</div>
.inner { padding: 10px; }
.right .inner { border-left: 1px solid #ccc; }
Upvotes: 5