float and clear
float property places block elements to the left or right of their containing elements. It takes the following values:
none - The default value. The element is not floated:
left - The element is floated to the left in its containing element:
right - The element is floated to the right in its containing element:
Floated elements are taken out of normal flow, but they continue to occupy space in the page layout, unlike absolutely positioned elements.
All these examples can be seen in Positioning/Demos/float.html and Positioning/Demos/float-styles.css.
Open Positioning/Demos/float.html in the browserand click on some of the links at the top to change the
clear property is used to force elements to move below floated elements. It takes the following values:
none - The default value. The element is not cleared:
left - The element is forced below all elements floated left in its containing element:
right - The element is forced below all elements floated right in its containing element:
both - The element is forced below all floated elements in its containing element:
These examples can be seen in Positioning/Demos/clear.html and Positioning/Demos/clear-styles.css.
Open Positioning/Demos/clear.html in the browser and click on the links at the top to change the
Layouts with float and clear
Before the development of more sophisticated CSS layout systems,
clear were used to create entire website layouts, but this is no longer recommended.
float, clear, and ::after
Sometimes the floated element is so big that when it is taken out of the flow, it extends beyond the height (which adjusts automatically for its content in normal flow) of its containing element. To fix this, it is possible to give the height a fixed value (e.g.,
400px), but this is not great for fluid pages with containers that may shrink and grow depending on the width. The solution is to use the
::after pseudo-element in combination with the
The syntax is:
This adds a cleared block pseudo-element at the end of the container element. We use an empty string (
"") because we don't want the pseudo-element to be visible to the user. The cleared pseudo-element must stay below any floated elements, so it keeps the height of container from becoming smaller than the floated element. See the demo below for an example: