Here’s a quick tip that will be useful for dealing with content that “overflows” outside of the normal boundaries. Any web designer I’m sure has encountered this issue at some point or another and you may be surprised to find how easy it is to correct. In this example we have an outer div “main content” area in green with a gray div “column” floated to the left with more content than the area will contain given the column’s width. As you can see in the example, the result is that the floated column extends beyond the lower boundaries of the outer div. This is less than ideal, especially when your site’s content is generated dynamically.

CSS Content Overflow

This first solution has stood the test of time and is known as the clearfix method. This technique uses the :after pseudo-element which is supported by CSS2 compatible browsers. Unfortunately, this doesn’t include Internet Explorer 7 and below. You may notice that there is actually two style blocks for our CSS and that is because we are using conditional comments that will target any Internet Explorer browser and use the proprietary hasLayout CSS attribute that must be commented or else your page will not validate.

<style type="text/css">

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

</style><!-- main stylesheet ends, CC with new stylesheet below... -->

<!--&#91;if IE&#93;>
<style type="text/css">
  .clearfix {
    zoom: 1;     /* triggers hasLayout */
    }  /* Only IE can see inside the conditional comment
    and read this CSS rule. Don't ever use a normal HTML
    comment inside the CC or it will close prematurely. */
</style>
<!&#91;endif&#93;-->

View Example #1

Another method uses an additional <div> element on the page with a style of “clear:both” which will force your container to accommodate the cleared element. While just as effective as any of the other methods, there is the concern of adding additional “meaningless” markup to your pages.

<div id="outer">
    ....
    <div style="clear: both;"></div>
</div>

View Example #2

Finally there is a relatively newly discovered technique which is quite easy to implement and is one which doesn’t require additional markup. It simply involves adding a “overflow: auto” property to the outer <div> element.

Half an hour of testing later, I was amazed to find Paul was 100% correct – as this example shows. It seems that reminding the outer <div> that it’s overflow is set to ‘auto’, forces it to think “oh yeah.. I’m wrapping that thing, aren’t I?”.

Alex Walker, sitepoint.com

View Example #3

So there you have it, three different techniques that will help you clear all of those pesky float issues.

More