CSS parent child divs and margins

greg's picture

He has: 1,581 posts

Joined: Nov 2005

When I have a parent div where the only content of that div is a child div, the child div's margins and margins of the elements in the child div don't work correctly.

so

<div id="outer">
<div id="inner">
<h2>inner div title</h2>
</div>
</div>

When I set a margin on the inner div, it moves the entire box down, including the outer div. If I put a margin on the H2, it also moves the entire box including the outer div.
This is the same when replacing the H2 for a <p>.

If I have a border on the inner div, that fixes it and the H2 margin moves around within the inner div and outer stays where it is, and margins on the inner div work as they should.
If I put plain textual content in either the inner or outer div (I tried a letter "a"), that also fixes it and the inner div and elements in the inner div then obey as they should.

What's the way to resolve this without using one of the above I mentioned as they are no good.

He has: 629 posts

Joined: May 2007

This is the correct behavior[1]. May not work in older IE if you have a "hasLayout" trigger[2] on the inner DIV though.

For normal browsers, adding a "block formatting context"[3] to the container DIV should fix it. Try "overflow: hidden;" or "overflow: auto;".

[1] http://www.w3.org/TR/CSS21/box.html#collapsing-margins
[2] http://www.satzansatz.de/cssd/onhavinglayout.html
[3] http://www.w3.org/TR/CSS21/visuren.html#block-formatting

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.