Reputation: 6706
Take a look at this two links:
http://jsfiddle.net/carloscalla/N8q27/10/
HTML:
<!DOCTYPE html>
<body>
<div id="container">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
<div id="container2">
<p>Hola</p>
</div>
</body>
CSS:
h1
{
background-color: green;
}
h2
{
background-color: blue;
}
#container
{
background-color: yellow;
border: solid black 2px;
}
#container2
{
background-color: orange;
border: solid blue 2px;
}
Rendered:
http://jsfiddle.net/carloscalla/N8q27/11/
HTML:
<!DOCTYPE html>
<body>
<div id="container">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
<div id="container2">
<p>Hola</p>
</div>
</body>
CSS:
h1
{
background-color: green;
}
h2
{
background-color: blue;
}
#container
{
background-color: yellow;
}
#container2
{
background-color: orange;
}
It is simple, when I apply border to the container, the child's padding is considered by the container, if I don't apply border(or padding works as well) it doesn't so when I apply background-color, there is a white space between the document objects.
Can anybody explain this? is there a way to solve it without applying padding or border to the container?
Upvotes: 0
Views: 136
Reputation: 59799
That is due to margin collapsing - in the first example the container holds two headers which each have default top/bottom margins of 16px, and because the top-margin of an in-flow block level element will always collapse with it's first in-flow block-level child, the <h1>
margin is collapsing beyond the container.
When you add a border to the container, you are preventing margin collapsing.
From the 2.1 spec:
The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.
Upvotes: 2
Reputation: 24703
This is margin collapse. Instead of applying a border, set overflow: auto;
. This resolves margin collapse.
DEMO jsFiddle
#container
{
background-color: yellow;
overflow:auto;
}
Upvotes: 2