What clearfix methods do you know? Provide some examples.

Technology CommunityCategory: CSSWhat clearfix methods do you know? Provide some examples.
VietMX Staff asked 3 years ago

Method 1. The Old School Way

Insert an empty element that has the clear property declared on it at the bottom of the container of floated elements.

.clear {
  clear: both;
}
<div class="container">
  <div class="el-1">I'm floated...</div>
  <div class="el-2">I'm also floated...</div>
  <br class="clear">
</div>

<div class="main">
  Bravo, sirs and madams. I'm in the clear.
</div>

Method 2: The Overflow Way

Using the overflow property on our .container, we can actually force the container to expand to the height of the floated elements.

.container {
  overflow: hidden; /* can also be "auto" */
}
<div class="container">
  <div class="el-1">I'm floated...</div>
  <div class="el-2">I'm also floated...</div>
</div>

<div class="main">
  Bravo, sirs and madams. I'm in the clear.
</div>

Method 3: The “clearfix” Class

The “clearfix” (which means fixing the clearing of floats) 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 CSS pseudo-elements ::before and ::after.

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

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1; /* ie 6/7 */
}
<div class="container clearfix">
  <div class="el-1">I'm floated...</div>
  <div class="el-2">I'm also floated...</div>
</div>

<div class="main">
  Bravo, sirs and madams. I'm in the clear.
</div>

Method 4: The Future contain-floats Value

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.