CSS Float
CSS Float
The float property is used to push an element to the left or right, allowing other content (like text) to wrap around it. Float was widely used for layouts before modern layout tools like Flexbox and Grid.
Today, float is still useful for simple cases such as wrapping text around images.
Float
The most common float values are:
left– float the element to the leftright– float the element to the rightnone– default (no floating)
img.avatar {
float: left;
margin-right: 12px;
}
In this example, text will wrap around the floated image.
Clear
When elements are floated, following elements may wrap around them. The clear property prevents an element from wrapping and forces it to move below the float.
clear: left– clears left floatsclear: right– clears right floatsclear: both– clears both left and right floats
.clearfix {
clear: both;
}
Float and Container Height
A common float issue is that a container may not expand to wrap floated children, because floated elements are removed from the normal flow.
A simple fix is to use a clearfix technique:
.clearfix::after {
content: "";
display: block;
clear: both;
}
Float Examples
Example 1: Wrap text around an image
.avatar {
float: left;
width: 80px;
height: 80px;
border-radius: 50%;
margin: 0 12px 8px 0;
}
Example 2: Two columns using floats (legacy layout)
.col {
float: left;
width: 50%;
box-sizing: border-box;
padding: 12px;
}
Modern layouts usually use Flexbox or Grid instead of float for columns.
Code Challenge
Goal: Create a simple layout using float and then clear the float.
HTML:
<div class="card clearfix"> <img class="avatar" src="avatar.png" alt="Avatar"> <h3>Float Example</h3> <p>This text should wrap around the floated image.</p> </div>
Task:
- Float the image to the left
- Add spacing around the image
- Use clearfix so the card contains the floated image
Try a Solution:
.avatar {
float: left;
width: 80px;
height: 80px;
border-radius: 50%;
margin: 0 12px 8px 0;
}
.clearfix::after {
content: "";
display: block;
clear: both;
}
.card {
padding: 16px;
border: 1px solid #ddd;
border-radius: 12px;
max-width: 560px;
}
What’s Next?
Next, you will learn how inline-block can be used to align elements side by side.