CSS Clear and Clearfix

The clear property stops an element from sitting beside a float, and the clearfix technique makes a parent wrap around its floated children.

When you float elements, later content may try to wrap up alongside them even when you would rather it start on a fresh line below. The clear property tells an element which sides must be free of floats before it is allowed to sit.

The clear values

  • left: the element moves below any left-floated elements
  • right: the element moves below any right-floated elements
  • both: the element moves below floats on either side
  • none: the default; no clearing is applied

Clear below a float

<!DOCTYPE html>
<html>
<head>
<style>
.box {
  float: left;
  width: 100px;
  height: 60px;
  background: #eee;
}

.footer {
  clear: both;
}
</style>
</head>
<body>

<div class="box">Floated content</div>
<div class="footer">Footer content</div>

</body>
</html>

The collapsing parent problem

A container whose children are all floated collapses to a height of zero, because floats are removed from normal flow. Any background or border on that container then disappears. The clearfix pattern solves this by forcing the parent to contain its floats.

The clearfix pattern

<!DOCTYPE html>
<html>
<head>
<style>
.box {
  float: left;
  width: 100px;
  height: 60px;
  background: #eee;
}

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}
</style>
</head>
<body>

<div class="clearfix">
  <div class="box">Floated content</div>
</div>
<p>Content after the container</p>

</body>
</html>
Note: A modern one-line alternative to the clearfix pseudo-element is display: flow-root on the parent, which creates a new block formatting context and contains the floats on its own.

The flow-root alternative

<!DOCTYPE html>
<html>
<head>
<style>
.box {
  float: left;
  width: 100px;
  height: 60px;
  background: #eee;
}

.container {
  display: flow-root;
}
</style>
</head>
<body>

<div class="container">
  <div class="box">Floated content</div>
</div>
<p>Content after the container</p>

</body>
</html>