Clearing Floats: An Overview of Different clearfix Methods

Clearing floats has long been a common necessity in front-end development. It’s no surprise then that over the years, we’ve been exposed to multiple methods for clearing floats, nowadays more commonly known as “clearfix methods”. Before we dig into the various methods, let’s take a look at the problem that clearfix methods attempt to solve.

The scenario: .el-1 and .el-2 are floated side by side inside a .container element, and there’s a .main element after .container.

The desired outcome: We want .container to expand to the height of its child elements (i.e. the taller of either .el-1 or .el-2), and we want .main to be after .container.

The actual outcome: .container collapses and takes on no height at all, as if there is nothing inside it, putting .main in an undesired location and potentially causing any backgrounds or borders on .container to be missing.

Based on the above scenario, our markup may look something like this:

<div>
  <div>A long string of stuff here...</div>
  <div>A short string of stuff here...</div>
</div>
<div>
  Some stuff here...
</div>

Then our CSS may look something like this:

.el-1, .el-2 {
  float: left;
  width: 50%;
}

.el-1 {
  /* styles for .el-1 here */
}

.el-2 {
  /* styles for .el-2 here */
}

.main {
  /* styles for .main here */
}

Finally, the result is as shown in this demo:

Continue reading %Clearing Floats: An Overview of Different clearfix Methods%

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s