Clear floating elements

All the UI developers are aware of table-less layouts. For table-less layouts, we use ‘div’s and often we use floats to position the ‘div’s. When used floats, clear floating is important to create layouts well. For many years we had been using a method of adding one element with the clear: both; style to clear floating. This was a simple method to perform the clear. This way of clear floating was fine but it introduced elements into the page that we really didn’t need.

Clear Floating css

HTML For clear floating

	
<div class="wrapper">
   <div class="left">Left</div>
   <div class="right">Right</div>
   <div class="clear"></div>
</div>

CSS for Clear floating

.left {
     float: left;
}
.right {
     float: right;
}
.clear {
     clear: both;
}

Today there are different ways of clearing floats. We will see the methods.

Clearing floats using pseudo elements

Pseudo elements can be used for clearing floats. Following css shows how to use the clearfix method.

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

This css will create a container :after the active element whose visibility is hidden, which will clear all pre existing floats and effectively reset the the page for the next elements with content. The clearfix allows the parent container to wrap it’s floated children.

For IE 6 and 7 support

The above mentioned clearfix solution is not sufficient for IE 6 and IE 7 support. So the following css do the tricks for IE 6 and IE 7. So we can use the following css for better browser compatibility.

* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

if we don’t have to support browsers less than IE 8, then the following css can be used.

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Clear floating with the use of CSS overflow property.

We have seen how to use clearfix method to clear floating. But we have another way which can be used to clear floating. The ‘overflow’ property in css can be used to clear floats. The following css shows the way.

.wrapper {
	overflow: hidden;
}

Add overflow: hidden; css for the wrapper element. This will do the magic for you.

Examples for clear floating

Fade in CSS3

To summaries, we can say, clearfix is a hack for clear floating. A clearfix is a way for an element to automatically clear its child elements, so that we do not need to add any additional markup for clear floating of the elements. Since use of float is very common in web design/development, a good clearing method is necessary. Hope this article helps you to better handle floats.

label, , , , , , , , , , , , , ,

About the author