Float was originally designed for text wrapping effects, allowing floated elements to avoid overlapping images and text (unlike absolute or fixed positioning).
A float creates a floatign box that moves left or right until it touches the container edge. Key characteristics:
- Floated elements leave the normal document flow
- Original space isn't preserved
- Elements align to the top in a single line
- Inline elements gain block-like properties (can set width/height)
Web layout fundamentally involves positioning boxes. Traditional approaches include:
- Normal flow (block/inline elements)
- Positioning
- Floating
Clearing floats becomes necessary when parent containers collapse (height becomes 0) due to floated children, causing subsequent elements to shift upward.
Clearfix methods:
- Extra DIV method:
<div class="container">
<div class="float-box">Content</div>
<div class="clear-div"></div>
</div>
<style>
.clear-div { clear: both; }
</style>
- Overflow method:
<div class="container" style="overflow:hidden">
<div class="float-box">Content</div>
</div>
- :after pseudo-element:
.clearfix::after {
content: '';
display: block;
clear: both;
height: 0;
visibility: hidden;
}
- Dual pseudo-elements:
.clearfix::before,
.clearfix::after {
content: '';
display: table;
}
.clearfix::after {
clear: both;
}