CSS Float & Clear
The float property was originally designed to allow text to wrap around images, mimicking print layout. However, for a long time, it became the primary method for creating multi-column web layouts before Flexbox and Grid arrived.
How Float Works
When an element is floated, it is taken out of the normal document flow and pushed to the far left or right of its container. Text and inline elements will wrap around it.
The Collapse Problem
If a parent element contains only floated children, its height collapses to 0. This happens because the children are removed from the flow, so the parent thinks it's empty. This is a common bug that breaks borders and backgrounds.
Clearing Floats
To fix the collapse, we need to "clear" the float.
- Old Way: The "clearfix" hack using a pseudo-element (
::after) withclear: both. - Modern Way: Use
display: flow-rooton the parent container. This creates a new Block Formatting Context (BFC) that contains the floats.
