CSS Float
The CSS float property was originally designed to allow images to sit beside text — like a newspaper layout where text wraps around a photograph. An element with float applied is taken out of the normal flow and pushed to the left or right side of its container, with other content flowing around it.
Although modern layout techniques like Flexbox and CSS Grid have replaced float for most layout purposes, float is still useful for text-wrap effects and is important to understand for reading older CSS code.
Float Values
| Value | Description |
|---|---|
left | Floats the element to the left; content wraps on the right |
right | Floats the element to the right; content wraps on the left |
none | Default. No floating — normal document flow |
Basic Float Example
img {
float: left;
margin: 0 20px 10px 0;
width: 200px;
}The image floats to the left and the paragraph text wraps around its right side — just like text wrapping around a photo in a magazine.
Float Right
.sidebar-note {
float: right;
width: 250px;
margin-left: 20px;
background-color: #f4f4f4;
padding: 15px;
border-radius: 6px;
}The clear Property
The clear property stops an element from wrapping around floated elements. It forces the cleared element to start below all floated elements above it.
.footer {
clear: both;
background-color: #2c3e50;
color: white;
padding: 20px;
}Common clear values: left clears left floats, right clears right floats, and both clears all floats on either side.
The Collapsed Parent Problem
When all children inside a container are floated, the parent container collapses to zero height because floated elements are removed from normal flow. This causes the parent's background and border to disappear.
.child-left { float: left; width: 48%; }
.child-right { float: right; width: 48%; }
/* Problem: .parent wrapping these two has zero height */Clearfix Solution
The clearfix technique uses a CSS pseudo-element to force the parent to wrap around its floated children.
.parent::after {
content: "";
display: block;
clear: both;
}Alternative Fix — overflow: hidden
.parent {
overflow: hidden;
background-color: #f0f4f8;
}Setting overflow: hidden on the parent also forces it to include floated children in its height calculation.
Two-Column Layout Using Float
.main-content {
float: left;
width: 65%;
padding-right: 20px;
}
.sidebar {
float: right;
width: 30%;
}
.container::after {
content: "";
display: block;
clear: both;
}Summary
The float property moves an element to the left or right, allowing surrounding content to wrap around it. The clear property stops an element from wrapping around floated neighbors. The collapsed parent issue is fixed using the clearfix pseudo-element trick or overflow: hidden. For new projects, Flexbox and CSS Grid are the preferred layout approaches — but understanding float is essential for working with and maintaining existing websites.
