Float in CSS
float is mainly used to create a column layout without the use of tables. A column layout can be easily created by
using float properties without needing to use CSS
positions at all. Like this -
Apart from that one of the most common uses for the float property is to float an image with text wrapping it. Like this -
The purpose of the CSS
float property is, to push a
block-level element to the left or right,taking it out of the flow in relation to other block elements. This allows naturally flowing content to wrap around the floated element.
The floated element is removed from the normal flow of the page, though remaining a part of the flow.
1. Text wrapping
Wrapping para around an image
In this example, as you can see I have applied
float: left on the
img tag and the image is then moved to the left(out of the normal flow) and the content of the
p tag behaves as if nothing has happened is part of the page flow.
Edit and comment the
float:left and see the result
2. Page layout
In this example, I tried to create a simple column layout using flow properties only.
Here, I have applied
float: left to the
float: right to
content and also gave width to them. If the width is not given then they will get placed on top of each other.
floated element should have an explicitly set
width to ensure that it behaves as expected
Here, you might have noticed that I have also provided
clear: both to the
clear: both, is a CSS hack that solves a persistent bug that occurs when two floated elements are stacked next to each other. When elements are aligned this way, the parent container ends up with a height of 0(zero), and it can easily break the layout resulting in two elements that overlap and collapse on each other. To complicate things further, the bug is inconsistent across browsers. The clearfix was invented to solve all that.
If the element can fit horizontally in the space next to another element that is floated, it will fit unless we explicitly apply
In the above example, if you try to remove
clear: both from the
footer then the footer will get placed itself into space next to the floated element.
clear property specifies on which sides of an element floating elements are not allowed to float.
clear can have following values:
left: elements are not allowed to Float on the left side in relation to other element.
right: elements are not allowed to Float on the right side in relation to other element.
both: elements are not allowed to Float on the either side in relation to other element.
float can have 4 valid values:
The most commonly-used values are
left and right. A value of
none is the default.