Grow height of parent div that contains floating nested divs

I can’t seem to auto-grow my parent div’s height based on its floating child divs. All the children are floating, to take up space horizontally, and then wrapping to the next line. There can be a changing number of floating children, and the parent has to auto-size its height. (The parent div serves as a background for all the floating divs). There is also a second div below the parent div that needs to be pushed down, so that it is below the floating divs.

It’s of major importance that the solution works in IE.


If the parent container only has floating children, it will have no height. Adding the following CSS to the parent container should help:

.parent {
    overflow:hidden;
    width: 100%;
}

Read this article for more: http://www.quirksmode.org/css/clearing.html.


You could insert a div that clears the floaters after the last child.

HTML:

<div style="clear: both"></div> <!-- This goes after the last floated element - no floating elements are allowed on either side of this. -->

fiddle: http://jsfiddle.net/Rc5J8/


You need to clear floated elements the height of their parents will collapse.

The current accepted answer is correct, however it's usually a better idea to clear floats by applying the clearfix hack or overflow: hidden to a wrapping parent element so that margins continue to functions as expected, and to get rid of an empty HTML element.

The overflow-method:

CSS:

.wrap { overflow: hidden }
.box  { float: left; }

Markup:

<div class="wrap">

    <div class="box">
        Content
    </div>

    <div class="box">
        Content
    </div>

</div>

The clearfix-method, as linked above:

CSS:

.cf:before,
.cf:after {
    content: " ";
    display: table;
}

.cf:after { clear: both; }
.cf { *zoom: 1; }

.box { float: left; }

Markup:

<div class="wrap cf">

    <div class="box">
        Content
    </div>

    <div class="box">
        Content
    </div>

</div>

You should use the clearfix technique on the containing div

http://www.webtoolkit.info/css-clearfix.html

That removes the need to add extra markup.


Adding the overflow css property on the parent element will fix the issue (no need for an empty & ugly div element to clear the float) :

.parentelement {
    overflow:auto;
    display: block;
    width: 100%;
}

I added the display and width properties because some browsers will need theses properties to be defined.