Chapter 18 of 33

Float & Clear

Open any newspaper or magazine: a photo sits on the left or right of a column, and the text flows neatly around it. CSS added float to do exactly that. For many years — before Flexbox and Grid existed — developers also stretched floats into a tool for whole page layouts (sidebars, columns, galleries), with lots of hacks to make them behave.

Today we use Flexbox and Grid for layout, but floats are still the correct tool for wrapping text around images, and you will meet float-based code in older projects, WordPress themes and exam papers. In this chapter we learn how float works, why it causes the famous "collapsing parent" problem, and the ways to fix it with clear, the clearfix hack and display: flow-root.


What is a Float?

A floated element is taken out of normal flow and shifted to the left or right edge of its containing block. The block boxes after it act as if it isn't there, but the lines of text inside them shorten to wrap around it.

The float property has these values:

ValueMeaning
noneDefault. The element is not floated.
leftFloat to the left edge; content wraps on its right.
rightFloat to the right edge; content wraps on its left.
inline-startFloat to the start side of the line (left in English, right in Arabic/Urdu).
inline-endFloat to the end side of the line.

The logical values inline-start and inline-end are supported in all current major browsers and adapt automatically to right-to-left languages.


Wrapping Text Around an Image

<article>
  <img src="taj.jpg" alt="Taj Mahal" class="photo">
  <p>The Taj Mahal is a white marble mausoleum in Agra. It was
  commissioned in 1631 by the Mughal emperor Shah Jahan ... (long text)</p>
</article>
.photo {
  float: left;
  width: 160px;
  margin: 0 16px 8px 0;   /* space between the image and the text */
}

Result:

┌────────────┐ The Taj Mahal is a white marble
│            │ mausoleum in Agra. It was
│   image    │ commissioned in 1631 by the
│            │ Mughal emperor Shah Jahan to
└────────────┘ house the tomb of his wife.
The text continues under the image once the image
ends, using the full width of the column again.

Notice two things:

  • The paragraph's box actually still starts at the left edge, underneath the image. Only its line boxes are shortened to avoid the float. If you gave the paragraph a background colour, you would see it extend behind the image.

  • The margin goes on the float, not the paragraph. A margin-left on the paragraph would be measured from the column edge (under the image), so it wouldn't create a gap.


How a Floated Element Behaves

  1. It becomes block-level. A floated <span> or <img> computes to display: block, so width, height and vertical margins work.

  2. It shrinks to fit its content if you don't give it a width.

  3. It moves as far left (or right) as it can, until it touches the containing block's edge or another float.

  4. Its top can't be higher than the top of the line or block it was written in.

  5. Margins of a float never collapse with neighbouring margins (margin collapsing was covered in Margin & Padding).

  6. Absolute and fixed positioning override it. A float can also be position: relative and nudged with offsets, but if you give it position: absolute or fixed, float computes to none and is ignored.

Several floats in a row

Multiple left floats line up side by side like books on a shelf. If there is not enough room, the next float drops down to the next position where it fits:

.tile {
  float: left;
  width: 30%;
  margin-right: 3%;
  height: 80px;
}
Container width = 100%
3 tiles × (30% + 3%) = 99%  → three tiles fit on one row
The 4th tile doesn't fit → it drops to the next row

This is how old-school "grid systems" (like Bootstrap 3) built columns. A tall tile can make the next floats "snag" on it and leave odd gaps — one of the reasons Flexbox and Grid replaced floats for layout.


The Collapsing Parent Problem

Here is the bug every float user hits. A parent contains only a floated child:

<div class="box">
  <div class="float-child">I am floated</div>
</div>
<p>Next paragraph</p>
.box {
  border: 2px solid black;
}

.float-child {
  float: left;
  width: 100px;
  height: 80px;
  background: lightgreen;
}

You expect the border to wrap around the green box. Instead, measured in Chrome:

.box height = 4px          ← just the top and bottom borders!
.float-child height = 80px ← sticks out below the parent
┌──────────────────────────────┐  ← .box (2px border, 0 content height)
└──────────────────────────────┘
│  green   │  Next paragraph      ← the next content wraps beside it
│  float   │
└──────────┘

Why? A float is out of normal flow. When the browser calculates the height of an ordinary block, it only counts in-flow content. The parent has no in-flow content, so its height is 0. The float hangs out of the bottom, and following content wraps around it — usually not what you wanted.

There are three standard ways to fix this.


Fix 1: The clear Property

clear says that an element must not sit next to earlier floats on the given side(s). The browser moves the element down until it is below those floats.

ValueMoves below…
noneDefault — may sit beside floats
leftEarlier left floats
rightEarlier right floats
bothEarlier floats on both sides
inline-start / inline-endLogical equivalents

A typical use: a footer that must start below a floated sidebar.

footer {
  clear: both;
}

In the old days, people fixed the collapsing parent by adding an empty element at the end of it:

<div class="box">
  <div class="float-child">I am floated</div>
  <div style="clear: both"></div>   <!-- old hack: extra markup -->
</div>

The empty div is in-flow and pushed below the float, so the parent grows to contain it. It works, but adding meaningless HTML just for styling is poor practice.


Fix 2: The Clearfix Hack

The clearfix generates that "empty clearing element" with CSS instead of HTML, using the ::after pseudo-element you met in Pseudo-classes & Pseudo-elements:

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}
<div class="box clearfix">
  <div class="float-child">I am floated</div>
</div>

How it works, step by step:

  1. ::after inserts a generated box as the last child of .box.

  2. content: "" is required, or the pseudo-element isn't created.

  3. display: block makes it a block (clear only applies to block-level boxes).

  4. clear: both pushes it below the float.

  5. The parent must now contain this in-flow block, so its height grows to reach below the float.

In our Chrome test, the parent's height changed from 4px to 84px (80px float + 2px top border + 2px bottom border).


Fix 3: display: flow-root (The Modern Way)

.box {
  display: flow-root;
}

One line, no hacks. In our test this also gave a height of 84px. display: flow-root makes the element a normal block that establishes a new block formatting context. It has been supported in all major browsers for years, and it is the recommended fix today.

What is a block formatting context (BFC)?

A block formatting context is an independent layout region in which block boxes are laid out and floats interact. Floats inside a BFC stay inside it, and floats outside it can't intrude into it.

An element that creates a BFC has three useful properties:

  1. It contains its floats — its height includes floated children. (That's our fix.)

  2. It doesn't overlap outside floats. Instead of its box running underneath a neighbouring float, the whole BFC box sits beside it. In our test, a flow-root box placed after an uncontained float started at x = 102px — right after the float — and became narrower, instead of starting at x = 0.

  3. Its children's margins don't collapse through it with the margins outside.

Many things create a BFC: display: flow-root, floats themselves, absolutely positioned elements, inline-block, table cells, flex and grid items, and any block with overflow other than visible or clip. That's why the older trick overflow: hidden (or overflow: auto) on the parent also contains floats — but it has a side effect: anything that sticks out of the box (shadows, dropdowns) gets cut off or shows scrollbars. flow-root has no such side effect.


Comparison of the Fixes

TechniqueExtra HTML?Side effectsVerdict
Empty <div style="clear: both">YesPollutes markupAvoid
overflow: hidden / autoNoClips overflowing content or adds scrollbarsWorks, but be careful
Clearfix (::after with clear: both)NoUses up the ::after pseudo-elementFine, common in older code
display: flow-rootNoNoneBest today

A Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Float Demo</title>
  <style>
    body {
      font-family: sans-serif;
      max-width: 600px;
      margin: 20px auto;
    }

    .card {
      display: flow-root;           /* contain the float */
      border: 2px solid #1e3a8a;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 16px;
    }

    .avatar {
      float: left;
      width: 80px;
      height: 80px;
      margin: 0 12px 4px 0;
      border-radius: 50%;
      background: linear-gradient(135deg, #fbbf24, #ea580c);
    }

    .price {
      float: right;
      font-weight: bold;
      color: green;
    }
  </style>
</head>
<body>
  <div class="card">
    <div class="avatar"></div>
    <span class="price">₹499/month</span>
    <h3>Riya Sharma</h3>
    <p>Teaches Data Structures and C++.</p>
  </div>

  <div class="card">
    <div class="avatar"></div>
    <h3>Arjun Mehta</h3>
  </div>
</body>
</html>

What you will see: in each card, an orange circle sits on the left and the text runs beside it. The green price floats to the top-right of the first card. The second card has only a short heading, so without a fix its border would collapse to the height of the heading and the circle would hang out of the bottom into the page; with display: flow-root, both cards are tall enough to fully contain their circles. Try deleting the display: flow-root line to see the broken version.


Floats Today: When to Use Them

TaskBest tool
Text wrapping around an image or pull quotefloat
A row of navigation linksFlexbox
Sidebar + main contentGrid or Flexbox
Card galleryGrid (or Flexbox with wrap)
Centering thingsFlexbox or Grid

Also note: inside a flex or grid container, float has no effect on the items. You'll see how Flexbox lays out items in the next chapter, Flexbox.


Common Mistakes

  • Forgetting to contain floats, so the parent's background and border collapse. Use display: flow-root.

  • Putting the gap margin on the text instead of the float. The paragraph's box runs underneath the float, so its margin doesn't create a gap.

  • Using floats to centre something. There is no float: center.

  • Expecting a float to stay inside its parent on its own. Without containment, it can overlap the next section.

  • Applying clear to an inline element. clear only works on block-level boxes.

  • Combining float with position: absolute. Absolute wins and the float is ignored.

  • Building new page layouts with floats. Use Flexbox and Grid instead.


Interview / Exam Questions

1. What happens to a parent element whose only child is floated?

Its height collapses (to 0 content height), because floats are out of normal flow and are not counted when computing the height of an ordinary block. Its border and background don't surround the float.

2. What does clear: both do?

It prevents the element from sitting next to any earlier left or right floats. The element is moved down until its top border edge is below the bottom of those floats.

3. Explain the clearfix hack.

.clearfix::after { content: ""; display: block; clear: both; } generates an empty block-level box at the end of the parent and clears it below the floats. Since the parent must contain this in-flow box, its height grows to include the floats.

4. What is a block formatting context, and how do you create one?

A BFC is an independent layout region: it contains its floats, it doesn't overlap floats outside it, and its children's margins don't collapse with margins outside it. It is created by display: flow-root, floats, absolute/fixed positioning, inline-block, table cells, flex/grid items, and overflow values other than visible/clip, among others.

5. Why is display: flow-root preferred over overflow: hidden for containing floats?

Both create a block formatting context, but overflow: hidden also clips any content that extends outside the box (shadows, dropdowns, tooltips). flow-root creates the BFC with no other effect.

6. Three floated boxes each have width: 30% and margin-right: 5%. Do they fit on one line?

No. Each takes 35% of the container's width, so three need 105% > 100%. The third box drops below. (With margin-right: 3% they would need 99% and fit.)


Summary

  • float: left | right moves an element to one side and lets inline content wrap around it.

  • Floats are out of normal flow; following block boxes run underneath them, but their text lines wrap around.

  • A floated element becomes block-level and shrinks to fit its content.

  • A parent with only floated children collapses. Fix it with display: flow-root (best), the clearfix, or overflow.

  • clear pushes an element below earlier floats.

  • A block formatting context contains floats, avoids outside floats, and stops margin collapsing.

  • Use floats for wrapping text; use Flexbox and Grid for layout.