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?
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
Yes. You should clear your float when div's closing.
<div>
<div style="float:left">Floated Div</div>
<div style="clear:both;" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With