I have look for a while now on this problem and have not found a straight answer. When adding a margin top to an element, in my case it happens mostly with headings. In many occasions the margin-top is shared with the parent.
HTML
<div>
<h1>My title</h1>
</div>
CSS
div{
padding:20px;
}
h1{
margin-top: 20px;
}
The result of the previous code will also add a margin-top to the div, as if we had the following:
div{
padding:20px;
margin-top:20px; /*this one is implemented by the browser, not written on the code*/
}
A way to solve this is by adding overflow:auto
to the parent, in this case the div css has:
div{
padding:20px;
overflow:auto;
}
Although the previous example solves the problem, it is not clear to me WHY???. This has something to do with "collapsing margins", where apparently a margin is combined with the parent's margin. But why????
How do we know when a parent will collapse the margin of the child and when not, what is the purpose of this property of the blocks, or is it a bug?
Here's a JSFiddle demo of the problem.
And Here is a JSFiddle demo of the solution
Thanks.
Thank you all for your answers, @gaurav5430 posted a link with a very precise definition that I would like to summarize into this answer. As of why they decided that this elements should behave like this it is still unclear for me; but at least we were able to find a rule that applies to collapsing margins:
"In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero
Basically in our example on the original question, the biggest margin-top is the one of the <h1>
therefore taken and applied to the parent <div>
.
This rule is cancelled for:
That is the reason why overflow:hidden
solved the issue.
Thanks @gaurav5430; here is the reference: http://reference.sitepoint.com/css/collapsingmargins
Also thanks to @Adrift that posted very good resources, although I found @gaurav5430's answer more straight forward and easier to understand.