Floating left and right
Floating an element moves it to the side of a container. It also takes it out of flow, which is why the parent box doesn't expand to contain it.
Floats interaction with other floats
Note how the floats will appear out of order on the same line if floated in different directions.
Also note how the floats stack up and don't overlap. Floated elements will float to their configured side in the order they appear in the element tree. If there is note enough room vertically or horizontally they will be pushed down.
Here's that same example with a wider container:
Floats and line boxes
Line boxes flow around floats:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate.
Same example with display: inline-block
:
A float will move horizontally on the same line box it starts, rather than to the top of the containing box:
Floats and block boxes
Block boxes force following floats below them, but blocks ignore floats. Note how here the block element is behind the float. Also note the order of the floats on the second line.
Here's an example with a smaller block box, showing again how floats stack on top of each other in order:
Clearing floats
You can stop an element being next to a float with clear: left/right/both
. Note that you can only
clear in a block formatting context, e.g. this means you can clear a floated element around another float element
but you can't clear inline elements.
Containing floats
A float
is taken out of regular flow, so parents won't automatically expand to contain them:
You can solve this in a few ways:
Clearfix
Using the clearfix hack. This involves adding an element after the float
and setting it to clear
the float
.
overflow: auto
Creating a new block formatting context using overflow: auto
. This works because the spec says
that if an element establishes a new block formatting context it must not overlap the margins of any floats
in the same block formatting context.
display: flow-root
Creating a new block formatting context using the new and not as widely supported display: flow-root
.
This is a more semantic approach, and also won't result in undesired scrollbars from setting overflow
when you don't really want overflow.