CSS Clearing Methods
Why is clear (clearing) needed in CSS?
When you use float on an element (e.g., float: left), it exits the normal document flow. This can cause the parent element, containing nothing but float elements, to collapse in height.
To make the parent "notice" such children, you need to clear the float (clearing).
Main Float Clearing Methods
clear Property
Added to element after floated ones.
<div class="clearfix"></div>
.clearfix {
clear: both;
}
This works, but requires adding extra HTML, which isn't always convenient.
Clearfix Technique (pseudo-element)
Most popular and universal method.
.clearfix::after {
content: "";
display: table;
clear: both;
}
Applied to parent element containing floated child blocks.
<div class="container clearfix">
<div class="left-box" style="float: left;"></div>
<div class="right-box" style="float: right;"></div>
</div>
Avoids adding extra markup and automatically clears float
Using "overflow: hidden"
.container {
overflow: hidden;
}
- Works because
overflowcreates new block formatting context (BFC), which includes floated elements in height calculation. - Downside: may clip content with
position: absoluteor blocks extending beyond boundaries.
Modern Alternatives — Flexbox and Grid
If you use display: flex or display: grid, clearing isn't needed at all, because elements remain in flow and don't cause parent collapse.
.container {
display: flex;
}
Better to use them instead of float when possible.
Important!:
Don't confuse clear and clearfix. - clear is a property, - clearfix is a technique using clear inside pseudo-element.