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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…