CSS Float: Text Wrapping and Layout Hacks
Before Flexbox and Grid, CSS Float was the undisputed king of web layouts. Understanding how it breaks document flow—and how to fix it with clears—is a rite of passage for every frontend developer.
The Original Purpose: Text Wrapping
The float property was initially introduced in CSS for a very simple, print-design-inspired reason: allowing text to wrap around an image.
When you apply float: left; to an image, the browser takes it out of the normal vertical stacking flow and pushes it as far to the left as possible within its containing block. The text that follows in the HTML will naturally flow around the right side of the floated element.
The Layout Era and Parent Collapse
Web developers soon realized that if you float multiple elements (like a sidebar and a main content area), you could create multi-column layouts. However, this introduced a notorious bug: Parent Collapse.
Because floated elements are taken out of the normal flow, a parent container with only floated children will assume it has a height of 0px. Backgrounds and borders on the parent will collapse to the top, looking entirely broken.
Restoring Order: The Clear Property
To fix parent collapse and stop elements from wrapping around floated items, CSS provides the clear property.
- clear: left; No floating elements allowed on the left side.
- clear: right; No floating elements allowed on the right side.
- clear: both; The most common value. It pushes the element below any floating elements on both sides.
Modern Context: Do we still use Float?+
For Layouts? No. Modern CSS relies heavily on Flexbox for 1-dimensional layouts (rows or columns) and CSS Grid for 2-dimensional layouts. They are far more predictable and don't require clearfix hacks.
For Text Wrapping? Yes! If you have an article with an image and want the paragraph text to literally wrap around it, float remains the standard and correct tool for the job.
❓ Frequently Asked Questions
What exactly does the float property do?
The float property removes an element from the normal document flow and pushes it toward the left (left) or right (right) edge of its container. Text and inline elements that follow in the HTML will flow around the floated element.
What is "Clearfix" and why do I need it?
When all children of a container are float, the container "collapses" and assumes its height is zero. The clearfixhack uses the ::after pseudo-element on the parent container to create an invisible block at the end with clear: both, forcing the container to expand to contain its floated children.
.clearfix::after {
content: "";
display: table;
clear: both;
}Should I still use Float for web page layouts?
No. Historically, it was used to create columns and complex layouts because there were no other options. Today, you should use CSS Flexbox or CSS Grid to structure your page. Reserve float exclusively for wrapping text around images.
