Advanced15 min read

Floats & Clearing

Learn how the CSS float and clear properties work, including the classic clearfix hack, and understand when to use floats versus modern layout methods like Flexbox and Grid.

The Float Property

The float property was originally designed to let text wrap around images, similar to how text wraps around figures in print design. A floated element is taken out of the normal document flow and shifted to the left or right edge of its container.

Float values:

  • left — The element floats to the left; surrounding content flows around its right side.
  • right — The element floats to the right; surrounding content flows around its left side.
  • none — The default. The element does not float.
css
.image {
  float: left;
  margin-right: 16px;
}

When you float an element, it becomes a block-level box regardless of its original display value. Inline elements that follow a float will wrap around it, while block elements may slide up underneath the float unless they are cleared.

Clearing Floats

html
<style>
  .float-left {
    float: left;
    width: 150px;
    height: 100px;
    margin-right: 16px;
    background: #6366f1;
  }

  .clear-both {
    clear: both;
  }

  /* The clearfix hack — applied to the PARENT */
  .clearfix::after {
    content: "";
    display: table;
    clear: both;
  }
</style>

<div class="clearfix">
  <div class="float-left"></div>
  <p>This text wraps around the floated box.</p>
</div>
<p class="clear-both">This paragraph starts below the float.</p>

The Clear Property & Clearfix

The clear property prevents an element from sitting beside a floated element. It forces the cleared element to move below any preceding floats.

Clear values:

  • left — Clear past left-floated elements.
  • right — Clear past right-floated elements.
  • both — Clear past floats on either side.
  • none — The default; no clearing behavior.

A common problem with floats is container collapse. If all children of a container are floated, the container's height collapses to zero because floated elements are removed from normal flow.

The clearfix hack solves this by adding a pseudo-element after the container's content that clears the floats:

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

Today, Flexbox and Grid have largely replaced floats for layout purposes. Floats are still perfectly valid for wrapping text around images, which is their original and most semantic use case.

What problem does the clearfix hack solve?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.