Last Updated: February 25, 2016
·
923
· sweatypitts

A Better Clearfix

This is old news, but it pains me to see how many have not yet gotten the memo.

Using an empty div with a 'clearfix' class must end. It mucks up otherwise meaningful markup and is a pain in the ass if nothing else.

Here's a simplified, common scenario:

Your HTML:

<div class="side-by-side">
  <div>Floaty content</div>
  <div>More floaty content</div>
</div>

Your CSS:

.side-by-side {
  background: #eee;
}
.side-by-side div {
  float: left;
}
.side-by-side:after {
  content: "";
  display: block;
  clear: both;
}

See it in action.

We want .side-by-side to extend to the bottom of its contents and not collapse as if it were empty, so instead of adding a clearfix div as its last child node, we simply add this css rule using the :after selector.

Worried about browser support? IE8 and newer handle it fine and IE7 and older make up only 1.87% of the browser population.