CSS Float
Understand how floating elements work and how layouts were built before Flexbox & Grid.
What is CSS Float?
The CSS float property is used to position an element to the left or right of its container, allowing other content (like text) to wrap around it.
- Originally used for text wrapping around images
- Later used to create layouts
- Still important to understand for legacy code
Real-Life Example: Like a newspaper where text flows around an image.
CSS Float Values
left→ Element moves to the leftright→ Element moves to the rightnone→ Default (no floating)inherit→ Inherits from parent
Basic Float Example
Floating an Image
img {
float: left;
margin-right: 15px;
}
In this example, the image moves to the left and the text wraps around it on the right.
Creating Layouts Using Float
Before Flexbox and Grid, developers used float to create multi-column layouts.
Two Column Layout
.sidebar {
width: 30%;
float: left;
}
.content {
width: 70%;
float: right;
}
Note: This approach works but is harder to maintain compared to Flexbox.
CSS Clear Property
The clear property is used to control what elements are allowed to float beside an element.
clear: leftclear: rightclear: both
Clearfix Problem & Solution
Floating elements are removed from the normal document flow, which can cause parent containers to collapse.
Clearfix Solution
.clearfix::after {
content: "";
display: block;
clear: both;
}
Why it matters: Prevents layout breaking due to floated children.
When Should You Use CSS Float?
- Wrapping text around images
- Maintaining old projects
- Simple content alignment
Modern Tip: Use Flexbox or Grid for layouts whenever possible.
Best Practices for CSS Float
- Avoid floats for full page layouts
- Always clear floats
- Prefer Flexbox/Grid for responsiveness
- Use floats mainly for text wrapping
Pro Tip: Learn float to understand CSS history — not to replace modern layouts.