CSS Float and Clear
The float property is used for positioning and formatting content, e.g. let an image float left to the text in a container.
How Float Works
The float property can have one of the following values:
left- The element floats to the left of its container.right- The element floats to the right of its container.none- The element does not float (this is the default).
Example: Image Floating Left
css
img {
float: left;
margin-right: 20px;
}The Clear Property
The clear property specifies what elements can float beside the cleared element and on which side. The clear property can have one of the following values:
left- The element is pushed below any left-floating elements.right- The element is pushed below any right-floating elements.both- The element is pushed below both left and right-floating elements.none- The default. Allows floating elements on both sides.
When clearing floats, you should also add overflow: auto; to the containing element to fix layout issues. This is known as the "clearfix hack".
Example: The "clearfix" hack
css
.clearfix {
overflow: auto;
}
.box-after-float {
clear: both;
}Test Yourself with an Exercise
Which property is used to stop elements from wrapping around a floated element?