Last Updated: February 25, 2016
·
2.395K
· jm9000

How to stretch a container around a float

One common problem I've seen many developers encounter occurs when the height of a floating object exceeds that of the rest of the content. The container conforms to the height of the content, excluding the floating object:

Picture

As seen above, the intention of the developer was to have the green background surround both the image and text, but the image ended up overflowing. The desired appearance is:

Picture

What happened? Because the image is floating, it is taken out of the normal document flow. In this context, it takes up no space at all.

No need to resort to fixed height containers, or use of tables just yet. There are workarounds!

Method 1: Add "overflow: hidden" to the container. (live demo)

<div style="background:#557755;padding:5px;overflow: hidden">
<img style="float:left;margin:5px" src="michael_jackson.jpg" alt="Michael Jackson">
<b>Top 5 Michael Jackson Songs</b><br>
5. Beat it<br>
4. Billie Jean<br>
3. Black or White<br>
2. Man in the Mirror<br>
1. Thriller
</div>

Method 2: Add a 0 height clearing object to the flow. (live demo)

<div style="background:#557755;padding:5px">
<img style="float:left;margin:5px" src="michael_jackson.jpg" alt="Michael Jackson">
<b>Top 5 Michael Jackson Songs</b><br>
5. Beat it<br>
4. Billie Jean<br>
3. Black or White<br>
2. Man in the Mirror<br>
1. Thriller
<div style="clear: both; line-height: 0; height: 0;">&nbsp;</div>
</div>

Of the two, method 1 is more simple to implement, but I've found method 2 to have a higher success rate with less CSS conflicts, and works with the infamous IE6. In most cases method 1 should be sufficient, but keep method 2 handy for those few cases where it doesn't.

3 Responses
Add your response

Thanks! Another solution: http://jsfiddle.net/hbA35/5/

over 1 year ago ·

@jverdeyen That's one I haven't seen before. I like it!

over 1 year ago ·
over 1 year ago ·