Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use "float: left" in a div without breaking the containing element's height?

It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}
<div class="portfoliosite">
    <div class="portfoliothumbnail"><!-- Img tag goes here --></div>        
    <p class="portfoliotitle">AwesomeSite.Com</p>
    <p class="portfoliodescription">An awesome site I did. It launched on Jan 1, 2009</p>        
</div>

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

like image 797
Joshua Carmody Avatar asked Feb 19 '09 03:02

Joshua Carmody


2 Answers

Add overflow: auto on the containing element:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
    overflow: auto;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}
<div class="portfoliosite">
    <div class="portfoliothumbnail"><!-- Img tag goes here --></div>        
    <p class="portfoliotitle">AwesomeSite.Com</p>
    <p class="portfoliodescription">An awesome site I did. It launched on Jan 1, 2009</p>        
</div>

See: http://www.sitepoint.com/blogs/2005/02/26/simple-clearing-of-floats

like image 107
Lee Henson Avatar answered Sep 28 '22 11:09

Lee Henson


Yes. You should clear your float when div's closing.

<div>
  <div style="float:left">Floated Div</div>
  <div style="clear:both;" />
</div>
like image 24
David Avatar answered Sep 28 '22 13:09

David