views:

64

answers:

2

I have created some <div> tags and am setting it to contain two <div> tags that are floated to both sides of the <div>.
I noticed when I tried to set a background color that the containing <div> was not properly wrapping around the <div>s that its supposed to contain. I would like to know why this happens.

I have seen a similar question here http://stackoverflow.com/questions/611220/why-are-these-div-tags-not-nesting-properly but no one has explained why this happens in any of the answers.

+3  A: 

When you float the inner divs, you take them out of the normal document flow, so basically your containing div has no content and no height.

You can solve it by adding a:

overflow: hidden;

to the outer div (just one possible solution).

jeroen
Jeroen's solution works well. You can also use an empty element such as <br class=clear /> under your inner divs and put clear:both for the clear class in your stylesheet. (if hidden overflow is a problem for your layout)
edl
@edl, true, but I prefer the overflow solution as `clear:both` tends to clear more than just the containing box.
jeroen
@jeroen agreed. :) I also prefer the overflow solution. Just depends on the individual application.
edl
@edl, absolutely, there´s no magic bullet for every situation.
jeroen
A: 

Add style="overflow:hidden;width:100%" to the containing div

I think style="overflow:hidden;" is enough for most browswers, I seem to remember some IE needing the width to be set.

Matt Dotson
Only when in quirksmode and you don't want to have that.
BalusC
@BalusC, no, in IE6 (all modes) the element needs to get *layout* to contain its floats. Setting a `width` will do that, though I prefer `zoom: 1`. In IE7, `overflow` already gives the element layout.
mercator
@mercator: Oh, I forgot that IE6 ever existed. But yes, you're right :)
BalusC