CSS Float & Clear

Difficulty: Beginner

Question

How do CSS floats work? What is the clearfix hack?

Answer

Float was originally for text wrapping around images, later used for layouts (before Flexbox/Grid).

float: left/right removes the element from normal flow and pushes it to the left/right. Following content wraps around it.

Problems: - Parent collapses (no height) when all children float - Solution: clearfix hack or overflow: hidden on parent

clear: left/right/both prevents an element from wrapping next to floated elements.

Modern CSS: Use Flexbox/Grid instead. Floats are still useful for text wrapping around images.

Code examples

Float Basics and Clearing

/* Float an image, text wraps around it */
.article img {
  float: left;
  margin: 0 1rem 1rem 0;
}

/* Clear: stop wrapping */
.article .section {
  clear: both;
  /* This element starts below any floats */
}

/* Problem: parent collapses */
.parent {
  border: 1px solid red;
  /* If all children are floated,
     parent has 0 height! */
}
.parent .child {
  float: left;
  width: 50%;
}

Floated elements are removed from normal flow. The parent doesn't know about them, so it collapses to zero height.

Clearfix Solutions

/* Solution 1: Clearfix pseudo-element (classic) */
.clearfix::after {
  content: '';
  display: table;
  clear: both;
}

/* Solution 2: overflow on parent */
.parent {
  overflow: hidden;
  /* or overflow: auto */
  /* Creates a Block Formatting Context */
}

/* Solution 3: display: flow-root (modern) */
.parent {
  display: flow-root;
  /* Best solution - explicitly creates a BFC
     without side effects */
}

/* Using clearfix */
<div class="clearfix">
  <div style="float: left;">Left</div>
  <div style="float: right;">Right</div>
</div>
<!-- Parent now wraps floated children -->

display: flow-root is the modern clearfix. It creates a Block Formatting Context (BFC) that contains floats without side effects like clipping overflow.

When Floats Are Still Useful

/* Text wrapping around image - float's original purpose */
.article {
  max-width: 600px;
}
.article img {
  float: left;
  width: 200px;
  margin: 0 1rem 0.5rem 0;
  border-radius: 0.25rem;
}
.article p {
  /* Text wraps around the image */
}

/* Drop cap effect */
.article p:first-of-type::first-letter {
  float: left;
  font-size: 3rem;
  line-height: 1;
  padding-right: 0.5rem;
  font-weight: bold;
  color: #1a56db;
}

/* For layouts, use Flexbox or Grid instead */
.layout {
  display: flex; /* not float! */
}

Float is still the best solution for text wrapping around images and drop caps. For everything else, use Flexbox or Grid.

Key points

Concepts covered

Float, Clear, Clearfix, Block Formatting Context, Legacy Layout