CSS Float and Clear
Float is a property that lifts an element to the left or right edge of its container. Content that follows the floated element wraps around it.
Float the picture left
The floated picture moves to the left edge of the page. The table after it starts beside the picture instead of below it.
.pic {
float: left;
}Space around the float
Margins on the floated picture keep the wrapped content at a distance. The right margin faces the table beside the picture.
.pic {
float: left;
margin-right: 12px;
margin-bottom: 8px;
}Clear the float
The clear value pushes the demo paragraph below the floated picture. No content wraps beside the picture at that point in the page.
.pic {
float: left;
}
#demo {
clear: both;
}Example
.pic {
float: left;
margin-right: 12px;
margin-bottom: 8px;
border-radius: 8px;
}
#demo {
clear: both;
}Key points
- Float lifts an element to one edge, and later content wraps around it.
- clear: a property that pushes an element below a floated element
- Use clear: both to push an element below floats on either side
- A floated element leaves the normal flow, and its parent can collapse around it.
- The float value none is the default, and it keeps an element in the normal flow.
In this example, the picture floats to the left edge of the page. Its right and bottom margins keep the wrapping content at a distance. The radius value rounds the corners of the picture. The demo paragraph clears the float, so it starts below the picture.
Note
Modern page layouts are usually built with flex and grid.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does clear: both do?