How do CSS floats work?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#CSS #HTML

Brief Answer

  • float aligns an element to the left/right edge; adjacent text and inline content wraps around it.
  • Flow changes: the container may collapse because floats are taken out of normal flow.
  • Control wrapping with clear, and fix container height via overflow:auto, display: flow-root, or clearfix.

Full Answer

What float does

  • Values: left, right, none.
  • The element sticks to a side; surrounding content wraps.

Mini example:

.img { float: left; margin: 0 8px 8px 0; }

Wrapping and clear

  • clear: left|right|both — prevents wrapping from specified sides.

Mini example:

.block { clear: both; }

Container collapse

  • A parent without inline content may ignore float height.

Fix options:

.container { overflow: auto; }
/* or */
.container { display: flow-root; }

clearfix via pseudo‑element

Classic way to close the flow:

.container::after {
  content: "";
  display: block;
  clear: both;
}

Common pitfalls

  • Forgetting clear — content overlaps floats.
  • Using floats for complex layouts — prefer Flexbox or Grid.
  • Fixed sizes without wrapping considerations — breaks responsiveness.

Modern alternatives

  • Use display: flex and display: grid for layout.
  • Keep float for small, local tasks (image wrapping, similar cases).