This page covers float and clear. Floats were once the main way to create
layouts; now Flexbox and Grid are preferred. Floats are still useful for text wrapping around images. Each example
shows output and code.
float: leftA floated element is removed from normal flow and pushed to the left (or right). Content below wraps around it.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. The floated box sits on the left and text wraps around it.
.box {
float: left;
width: 100px;
}
float: left takes the element out of normal flow and moves it to the
left. Block content that follows wraps around the right and bottom of the floated element. The floated element
must have a width (or it will shrink-wrap).
float: rightSame as left, but the element is pushed to the right. Text wraps around its left side.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. The box floats to the right and text wraps on the left. Ut enim ad minim veniam, quis nostrud exercitation.
.box {
float: right;
width: 100px;
}
clear — stop wrappingUse clear on an element to force it below any preceding floats. Values:
left, right, both, none.
Text wraps here…
This paragraph has clear: both — it starts below the float.
.below-float {
clear: both;
}
clear: both means “do not allow left or right floats beside me.” The
element is pushed down below any floats. Use clear: left or clear: right if you only
care about one side.
When all children are floated, the parent “collapses” (height becomes 0) because floats are out of flow. Use a clearfix on the parent to make it wrap its floated children.
The green border shows the parent; it now contains the floats.
Code.parent::after {
content: "";
display: table;
clear: both;
}
overflow: hidden or overflow: auto on the parent (creates a block formatting context
and contains floats).
Multiple elements with float: left line up horizontally (like columns). When there’s
not enough space, they wrap to the next line.
.parent::after { content: ""; display: table; clear: both; }
.child { float: left; width: 80px; }
float: left / float: right — removes element from flow; content wraps around it.
clear: left / right / both — element starts below preceding floats.
.parent::after { content: ""; display: table; clear: both; } — parent
contains floated children.