What is a clearfix?

Before getting to this solution I would like to distinguish between the float and the clearfix, Which a lot of people get mixed up most of the time.

float is meant to do stuff like float images next to long runs of text, but lots of people used it as their primary layout mechanism. Since it wasn’t really meant for that, you need hacks like “clearfix” to make it work.

These days display: inline-block is a solid alternative, although more modern browsers are coming with even more useful layout mechanisms under names like flexbox, grid layout, etc.

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<8 support, the following is fine too:

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

Normally you would need to do something as follows:

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

With clearfix, you only need the following

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