Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is a clearfix?

I was looking through some website's code, and saw that every <div> had a class clearfix.

After a quick Google search, I learned that it is for IE6 sometimes, but what actually is a clearfix?

Could you provide some examples of a layout with a clearfix, compared to a layout without a clearfix?
by

2 Answers

espadacoder11
The clearfix allows a container to wrap its floated children. Without a clearfix or equivalent styling, a container does not wrap around its floated children and collapses, just as if its floated children were positioned absolutely.

There are several versions of the clearfix, with Nicolas Gallagher and Thierry Koblentz as key authors.

If you want support for older browsers, it's best to use this clearfix :

.clearfix:before, .clearfix:after {
content: "";
display: table;
}


.clearfix:after {
clear: both;
}

.clearfix {
zoom: 1;
}

In SCSS, you could use the following technique :

%clearfix {
&:before, &:after {
content:" ";
display:table;
}

&:after {
clear:both;
}

& {
*zoom:1;
}
}

#clearfixedelement {
@extend %clearfix;
}

If you don't care about supporting older browsers, there's a shorter version :

.clearfix:after {
content:"";
display:table;
clear:both;
}
RoliMishra
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<8 support, the following is fine too:

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


Normally you would need to do something as follows:

<div>
<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->
</div>


With clearfix, you only need the following:

<div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
</div>

Login / Signup to Answer the Question.