CSS Clearing Floats Snippet

Sometimes with float-based layouts you get to points where you need to clear the floats to get the desired layout you need.

An element that has the clear property set will not move up next to the floated element, but will move itself down past the floats.

Here is a small CSS snippet to clear floats on your page.

.clearfix:after {  /* fr Firefox, IE8, Opera, Safari, etc. */
    content: ".";  
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
 
* + html .clearfix { /* for IE7 */
    display: inline-block;
}
 
* html .clearfix { /* for IE6 */
	height: 1%;
}


Here's a smaller version from Nicolas Gallagher.

/* For modern browsers */
.clearfix:before,
.clearfix:after {
    content:"";
    display:table;
}

.clearfix:after {
    clear:both;
}

/* For IE 6/7 (trigger hasLayout) */
.clearfix {
    zoom:1;
}

Now all you have to do is add the clearfix class to the element you want to clear.

<div class="clearfix">

</div>

Clearfix With Overflow:hidden

Here is a tip sent to me by @teddytrised who said that if you have a width on a div you can clear the float by adding an overflow hidden.

View this JSFiddle to see hows it works.

CSS Clear With Overflow Hidden

Advertise here 50% Off

Comment