3

Please see this fiddle http://jsfiddle.net/a506r2gh/

There is a weird padding appearing between body and "header" division. And it goes away if I add a border to the "header" div. Margin collapse and body margin do not seem to be the problem here.

Thanks in advance!

Here is the html

<body>
    <div class="header">
        <a href="#"><div class="photo"></div></a>
        <div class="footer"></div>
    </div>
</body>

Here is the css

body {
    margin:0; padding:0; background: #999;
}
.header {
    background-color: #422;
    /* border: solid 1px red; */ /* problem goes away if I add border to header */
}
.header .photo {
    width: 150px;
    height: 150px;
    border-radius: 75px;
    background: #660;
    margin:50px auto;
}
.footer {
    height:50px;
    background: #303;
    margin-bottom:50px;
}
3
  • 2
    .header .photo has margin-top: 50px hence the gap. Give overflow: auto to .header
    – anpsmn
    Dec 25, 2014 at 12:14
  • 1
    Thanks @anpsmn. That works. Why does the padding go away when I add that border on the div? Dec 25, 2014 at 12:17
  • 1
    The padding is infact the margin on .photo that collapses with #header and renders outside it.
    – Salman A
    Dec 25, 2014 at 12:21

1 Answer 1

4

The .photo element inside your header has a top and bottom margin of 50px, which is affecting the parent.

To prevent this, add overflow: auto to the .header.

There are also several other ways that you can solve this.

I can't speak to why this happens, but here's a quote from MDN about the behavior:

If there is no border, padding, inline content, height, or min-height to separate a block's margin-top from its margin-bottom, then its top and bottom margins collapse.

Source

1
  • 1
    Oh... I see from the MDN quote, why adding the border affects this! Brilliant :) Thank you. Dec 25, 2014 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.