Episode 4 of 23

Floating Elements

Learn how the CSS float property works — taking elements out of normal flow and wrapping text around them.

Floating Elements

The float property was one of the first CSS tools for creating layouts. While modern techniques like Flexbox and Grid have largely replaced floats for layout, understanding floats is still important for text wrapping and legacy code.

What Does Float Do?

When you float an element, it is taken out of normal flow and pushed to the left or right of its container. Surrounding content (like text) wraps around the floated element.

Float Values

ValueBehavior
float: left;Element floats to the left; content wraps on the right
float: right;Element floats to the right; content wraps on the left
float: none;Default — element is in normal flow

Basic Example

<!-- HTML -->
<img src="photo.jpg" class="float-left" alt="Photo">
<p>This text will wrap around the image on the right side.
   The image floats to the left and the paragraph flows 
   around it naturally, like text in a magazine layout.</p>
/* CSS */
.float-left {
    float: left;
    width: 200px;
    margin-right: 16px;
    margin-bottom: 8px;
}

How Float Affects the Element

  • The element is removed from normal document flow
  • It shifts to the left or right edge of its container
  • Block elements below it move up to fill the space
  • Inline content (text) wraps around the floated element
  • The floated element behaves like an inline-block (it respects width/height)

Floating Multiple Elements

When you float multiple elements in the same direction, they stack horizontally:

.box {
    float: left;
    width: 100px;
    height: 100px;
    margin: 8px;
    background: #6c5ce7;
}
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>

All three boxes will sit side by side from left to right.

The Container Collapse Problem

When all children of a container are floated, the container's height collapses to zero because floated elements are removed from flow:

<div class="container">
    <div class="box" style="float:left">Floated</div>
</div>
<!-- The .container has 0 height! -->

We'll solve this in the next episode with clearing floats.

Key Takeaways

  • float: left or float: right takes an element out of flow
  • Surrounding text wraps around floated elements
  • Multiple floated elements stack side by side
  • Floated children cause their parent container to collapse
  • Floats are still useful for text wrapping but not for modern layouts