If you have ever worked with CSS float, I am absolutely sure you have experienced the interesting and sometimes strange effects it has on the content that follows. In this post I have summarised different ways to clear CSS floats along with some helpful tips for older versions of IE.
Perhaps, the easiest way to clear floats is to float the container element itself. But unfortunately this method only works in a limited number of circumstances, as floating the parent element may have undesirable effects on the layout. For instance, if the design requires container element to be horizontally centered, this method doesn't work at all.
This approach uses the CSS overflow property on the container element to clear CSS floats. If you add "overflow: hidden" to the containing element, it will automatically adjust its height and take the floated children into account.
.clear-float-container { overflow: hidden; } /* FIX for IE6 Use height: 1%; or zoom: to trigger hasLayout in IE 6. My recommendation is to serve this only to IE 6 through a separate style sheet included with conditional comments. */ .ie6.clear-float-container {height: 1%;}
There are however, some drawbacks to using the overflow method to clear CSS floats:
In this approach, we add an extra <div> tag with the following CSS at the end of the container element. Some developers also use <span> or <br /> tags but 'div' is the most common as it has no browser default styling. Although an easy option, this method is not recommended as it adds non-semantic code to the mark-up and is a perfect recipe to upset the SEO team.
CSS div.clear-float { clear:both; font-size:0; height:0; } HTML <div class="container"> <div id="float-left"> some content here… </div> <div id="float-right"> some other content here… </div> <div class="clear-float"></div> </div>
In this approach, we use the CSS3 pseudo-class ":after" to generate on-the-fly content after the containing element and use it to clear floats. An important thing to do with this approach is to hide the generated content so it doesn't use up any screen space. However, this being a CSS3 feature, the obvious drawback is that this is not supported by older browsers.
. clear-float-container:after{ content: "."; display: block; height: 0; clear: both; visibility: hidden; } /* FIX for IE6 Use height: 1%; or zoom: to trigger hasLayout in IE 6 & 7. My recommendation is to serve this only to IE 6 through a separate style sheet included with conditional comments. */ .ie.clear-float-container {height: 1%;}
So to summarize, there really is no simple, one-size-fits-all solution to clearing CSS float. But almost any float clearing issue can be resolved with one of the above methods.