CSS - Clearing floated elements

css

// Different ways to clear float:

// Using "clear: both"
.clear {
  clear: both;
}

This method was the go to method once upon a time. It works, plain and simple. 
However, in these modern times of separating content from style, and trying to 
keep things as semantic as possible, this method is generally frowned upon by 
many because it either means having to use an extra DIV for clearing or having
to add this class to an element.

// Using "overflow:auto" or "overflow:hidden"
.container {
  overflow: hidden; /* can also be "auto" */
}

The .container expands to the height of our floated elements, background colours, 
borders, and background images will fill it up if applied, and all is well.

One of the main drawbacks of this method is the fact that any child content that 
pokes outside the container element is going to either get clipped (assuming a 
value of hidden) or is going to cause scrollbars to appear (assuming a value of 
auto). This is better than our previous solution, but still far from ideal. 

// Using the “clearfix” class

Defines a .clearfix class in our stylesheet that we can apply to any 
float-containing element. This will force the container element to expand, 
pushing subsequent elements beneath it. It uses the awesome CSS pseudo-elements 
::before and ::after.  This … generates pseudo-elements and sets their display 
to table. This creates an anonymous table-cell … The :after pseudo-element is 
used to clear the floats. As a result … the total amount of code needed is 
reduced. The CSS looks like this:

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

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1; /* ie 6/7 */
}

If you don’t need to support anything below IE8, you could get by with just the 
following:

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

Interestingly, the W3C specification has added a new value to the min-height 
property (and to other min/max properties), in order to help solve this problem. 
It looks like this:

.container {
  min-height: contain-floats;
}

This basically will do the same thing as the clearfix or the overflow method, 
but with a single line of code and without any of the drawbacks we’ve discussed. 
And of course, you could create a separate reusable clearfix class that this 
could be attached to, and just use it once in your CSS.  It doesn’t appear that 
any browser supports this value as of yet, but it’s certainly something to keep 
an eye on.

See https://www.sitepoint.com/clearing-floats-overview-different-clearfix-methods/
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License