Cyrus Yip's blog

What is Clearfix in CSS

Cyrus Yip

Float can be used to lay out elements. Clearfix is a method used to fix the zero-height container issue caused by floated elements.

Here is an example of arranging items vertically using float (live preview):

1
2
3
4
5
6
<div class="container clearfix">
  <div class="item item1">item1</div>
  <div class="item item2">item2</div>
  <div class="item item3">item3</div>
</div>
<div class="outer">outer element</div>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.item {
  border: 1px solid red;
  width: 60px;
  height: 60px;
  float: left;
}

.container {
  border: 1px solid green;
}

Three items are properly arranged, but the outer element is at the right side of item3.

1
item1 | item2 | item3 | outer element

The outer element should be under all items.

1
2
3
item1 | item2 | item3 |

outer element

Since three items are floated, they are removed from the normal flow. As a result, .container contains nothing, so its height is 0. That’s why the outer element isn’t under three items. Here is the classic method for fixing the height:

1
2
3
4
5
.clearfix::after {
  content: '';
  display: block;
  clear: both;
}

Breakdown:

The classic method is obsolete and difficult to understand. Here is the modern and simpler method:

1
2
3
.clearfix {
  display: flow-root;
}

display: flow-root makes the container establish a block formatting context, which contains internal floated elements. For more details on block formatting context, see What is Block Formatting Context (BFC) in CSS.


Note that float layout is hacky and obsolete. Use flexbox or grid instead.

Tags: