CSS margin-top of <h1> affects parent's margin

Viewed 39966

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.

5 Answers

Putting a border to the parent div solve the problem, I use that if i don't want a visible border, it's works well

div.container {
    margin-top: 10px;
    border:  0.01px solid transparent;
}
h1 {
    margin-top: 50px;
}
Related