Web Development - CSS Float
CSS Float and Clear
The float property is used to position elements side by side or make text wrap around images.
The clear property controls how elements behave next to floated elements.
The Float Property
Use float to push an element to the left or right side of its container.
In this example, the image floats to the right, and text wraps around it.
Float Values
The float property can take these values:
left- floats the element to the leftright- floats the element to the rightnone- default; element does not floatinherit- inherits the float value from its parent
Example
Left and right floats:
<div style='float:left; width:45%; background-color:lightblue;'>Left</div>
<div style='float:right; width:45%; background-color:lightgreen;'>Right</div>
Try it Yourself »
Clearing Floats
When elements are floated, following elements may wrap around them.
Use the clear property to prevent this behavior.
clear: left;- no floating elements allowed on the leftclear: right;- no floating elements allowed on the rightclear: both;- no floating elements allowed on either side
Example
Clearing floats:
<div style='float:left; width:100px; height:100px; background:lightblue;'></div>
<div style='clear:left; background:lightgray; padding:10px;'>This div is below the floated box.</div>
Try it Yourself »
The Clearfix Hack
When a container holds only floated elements, its height may collapse. You can fix this with a "clearfix" - forcing the container to include its floats.
Example
Clearfix method:
.clearfix::after {
content: "";
clear: both;
display: table;
}
Try it Yourself »
Add the clearfix class to the parent container to keep it from collapsing.
Float Layout Example
Floats were once used to create entire web layouts. Here's a simple example of a two-column float layout:
Example
Two-column layout:
.container {
width: 100%;
overflow: auto;
}
.left {
float: left;
width: 70%;
background: lightblue;
}
.right {
float: right;
width: 30%;
background: lightgreen;
}
Try it Yourself »
Float with Images
One of the most common uses for float is making text wrap around images.
Example
Image with float:
<img src='pic_trulli.jpg' style='float:right; width:200px; margin:10px;'>
<p>The image is floated to the right, and the text wraps around it beautifully.</p>
Try it Yourself »
Clearing Floats with overflow:auto
Another way to fix collapsing containers is to use overflow: auto; on the parent.
Notes on Floats
Floats are useful for wrapping text and simple layouts, but modern designs and full-page layouts use Flexbox and Grid.
Next, you'll learn about CSS Flexbox - a modern, powerful way to align and distribute elements easily in one-dimensional layouts.