Value: left | right | inherit | none
- Floating an element will cause it to move to the left-most or right-most edge of its parent container.
- Floating removes the element from normal document flow and changes the stacking context.
- It will cause elements below it to shift accordingly.
Iteration 1 : float: none; /* Default */
We have three colored square boxes, which are rendered according to the document flow and are stacked one after the other.
Iteration 2 : float: right;
Floating the first red square to the right removes it from the document flow, hence the green square occupies the red square’s place as shown below.
Iteration 3 : float: left;
Interestingly if we float the red square to left then it will overlap the green square as shown below.
- The floated element has the higher stacking context, hence it’s being rendered on top of the non-floated element.
Iteration 4 : parent container collapsed
Applying, float: left to all the squares cause the container to collapse. Hence, you can not see the white background.
- As all the colored sqaure are floated they have the same stacking context and they are relative to each other.
Iteration 5 : prevent parent container collapsed using extra markup
We can add an extra an element, after all the floated squares and give it a style of clear:both as shown below. It will prevent the container from collapsing. Hence, you can see the white background.
Iteration 6 : prevent parent container collapsed using overflow property on the container
We can add overflow:hidden, overflow:auto to the container element as shown below. It will prevent the container from collapsing. Hence, you can see the white background.
Iteration 7 : prevent container collapsed using clearfix
clearfix is a technique to prevent the container collapsed as shown below.