CSS Float(Floating)
What is CSS Float?
CSS Float allows an element to be positioned to the left or right, causing other elements to wrap around it.
Float is often used for images, but it is also very useful for layout purposes.
How Elements Float
Floating elements are positioned horizontally, meaning they can only move left or right but not up or down.
A floated element will move as far left or right as possible until its outer edge touches the containing box or another floated element.
Elements following a floated element will wrap around it.
Elements preceding a floated element will not be affected.
If an image is floated to the right, the following text will wrap around its left side:
Example
img {
float: right;
}
Floating Elements Next to Each Other
If you place several floated elements together, they will float next to each other if space allows.
Here, we use the float property for an image gallery:
Example
.thumbnail {
float: left;
width: 110px;
height: 90px;
margin: 5px;
}
Clearing Floats - Using clear
After an element is floated, surrounding elements will rearrange themselves. To avoid this, use the clear property.
The clear property specifies that no floating elements are allowed on either side of the element.
Adding an image gallery to text using the clear property:
Example
.text_line {
clear: both;
}
More Examples
Add a border and margin to an image and float it to the right of a paragraph
Let's add a border and margin to an image and float it to the right of a paragraph.
Float headings and images to the right
Float headings and images to the right.
Float the first letter of a paragraph to the left
Change the style to float the first letter of a paragraph to the left.
Create a webpage without tables
Use float to create a webpage header, footer, left content, and main content.
All Float Properties in CSS
The numbers in the "CSS" column indicate the different CSS versions (CSS1 or CSS2) that define the property.
Property | Description | Values | CSS |
---|---|---|---|
clear | Specifies that no floating elements are allowed around the element. | left <br>right <br>both <br>none <br>inherit | 1 |
float | Specifies whether a box (element) can float. | left <br>right <br>none <br>inherit | 1 |