What is clearfix?

18 Jun

This was long overdue,I always quiz about clearfix and is something that I feel every Frontend Developer should know about. But surprisingly almost 50% of candidate could never answer this thing and hence this post

A clearfix is a way for an element to automatically clear its child elements, so that you don’t need to add additional markup. It’s generally used in float layouts where elements are floated to be stacked horizontally.

The clearfix is a way to combat the zero-height container problem for floated elements

A clearfix is performed as follows:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don’t require IE

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

Normally you would need to do something as follows:


    <div style="float: left;">Sidebar

    <div style="clear: both;">
 

With clearfix, you only need to

<div class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar

    

I hope this helps in understanding the magic behind clearfix.

Leave a comment