CSS Floats: Escaping the Document Flow
Before Flexbox and Grid, Floats ruled the web. Originally designed strictly to wrap text around images (like in print), developers hijacked them to build entire multi-column layouts, bringing the notorious "container collapse" problem with them.
The Core Mechanic: float
When you apply float: left; or float: right; to an element, it is pushed to the specified side of its container. Crucially, it is taken out of the normal document flow. Inline elements (like text) will wrap around it, but block-level elements will behave as if the floated element isn't there.
The Problem: Container Collapse
Because floated elements are removed from the normal flow, a parent container only containing floated children will assume it is completely empty. Its height collapses to zero. This destroys layouts, hiding backgrounds and borders.
The Solution: clear & clearfix
The clear property solves this. By applying clear: both; to an element, you force it to drop below all floated elements. The modern way to do this without adding empty, meaningless HTML tags is the clearfix hack. By using the ::after pseudo-element on the parent container, we virtually create a block element at the end that clears the floats, forcing the parent to expand.
❓ Frequently Asked Questions
Should I still use floats for layouts today?
Short answer: No. For page structures and columns, you should use CSS Flexbox or CSS Grid. They are more robust, easier to use, and don't cause container collapse issues.
However, you should still use `float` for its original purpose: wrapping text around an image or an element, just like in a magazine article.
What exactly does 'clear: both' do?
The `clear` property tells an element that it cannot have floating elements next to it. `clear: left` pushes it below left floats, `clear: right` below right floats. `clear: both` ensures the element moves below any previous floating elements.
Why does clearfix use 'display: table' or 'block'?
In the clearfix hack (`.clearfix::after`), we apply `content: ""` to generate a pseudo-element. However, by default, pseudo-elements are `inline` (like a span), and the `clear` propertyonly works on block elements. By changing it to `table` or `block`, we allow the `clear` property to take effect and stretch the container.
