Using CSS to make DIV go around Float

At some point, most HTML developers end up in a situation where they use the float:right and/or float:left property and then notice that the DIV going around it isn't wrapping the content anymore.

Broken Example

You can reproduce this in the physical world by holding an elastic band open with your fingers. Holding your fingers in the same position, pull them out from elastic band. With nothing left inside to hold the shape of the elastic, it shrinks back to it's original shape. This is what is happening with your outer DIV.

Hello World!

Working Example of the Solutions

The idea and easiest solution is to add overflow:auto; to the outer DIV:

<div style="border:1px solid red;width:500px;padding: 10px;">

Unfortunately, depending on your CMS, modifying the outer div may not always be possible. What you can do instead is to insert the following line before the last </DIV>:

<div style="clear:both;"></div>

Hello World!

Notice that the red border will then wrap around the content. Here is the full source code:

<div style="border: 1px solid red; width: 500px; padding: 10px;">Hello World!
<div style="float: left;"><img alt="" src="" /></div>
<div style="float: right;"><img alt="" src="" /></div>
<div style="clear:both;"></div>

You could further minimize the impact of the style with the following properties:

clear:both; height:1px; margin:0; padding:0;


Using CSS to make DIV go around Float — 2 Comments

  1. There are a few different ways to overcome this issue. My preferred method is option 3 of the methods shown here:

    The Easy Clearing Method uses a clever CSS pseudo selector (:after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class like “clearfix” to it. Then apply this CSS:

    .clearfix:after {
    content: ".";
    visibility: hidden;
    display: block;
    height: 0;
    clear: both;

    • Thanks for taking the time to share this solution. That is indeed a good way to work around the issue. Note that your solution uses CSS3. If backwards browser compatibility is important, one of the other solutions should probably be used instead.
      Thank again for sharing. That CSS tricks site is pretty useful. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *