tags:

views:

41

answers:

1

I have some unexplained weirdness with a nested DIV's margin "leaking" out of the parent container .

The following test case* probably explains it best:

http://jsbin.com/ibaze

The outer wrapper (red) doesn't start at the very top - unless there's a text node or overflow: auto; on that element. (Tested on Firefox and Safari.)

While overflow allows me to work around the issue, I'd quite like to know why it is happening in the first place. Any insights would be appreciated!

 * it's a minimal test case except for the script at the bottom, which merely illustrates the workarounds

+1  A: 

The reason why it is not working is that your vertical margin in CSS is collapsing, which is expected behavior.

Remove the margin from #inner, and instead specify a padding: 50px; to your #outer to get the desired result:

* {
    margin: 0;
    padding: 0;
}

body {
    color: white;
    background-color: blue;
}

#outer {
    padding: 50px;
    background-color: red;
}

#inner {
    background-color: green;
}

For more information on Vertical Margin Collapsing, I recommend you read the following article:

CSS - Auto-height and margin-collapsing

Andrew Moore
http://www.w3.org/TR/CSS2/box.htmlA good read to begin understanding the HTML Box model.
Philippe
**@Philippe:** Yes, but I tend not to link to W3C as some people find the standards documents a bit dry to read.
Andrew Moore
Thanks! Looks like I need to revisit the box model (it's been a while since I've done CSS stuff... ).