How to Use Float in CSS: Syntax, Examples, and Tips
Use the
float property in CSS to push an element to the left or right, allowing other content to wrap around it. The main values are left, right, and none to control the element's floating behavior.Syntax
The float property moves an element to the left or right side of its container, letting text or inline elements wrap around it.
float: left;— floats the element to the left.float: right;— floats the element to the right.float: none;— default, no floating.clearproperty is often used with float to control wrapping.
css
selector {
float: left | right | none;
}Example
This example shows an image floated to the left with text wrapping around it.
css
html, body {
font-family: Arial, sans-serif;
padding: 20px;
}
img {
float: left;
margin-right: 15px;
width: 150px;
height: 100px;
border: 2px solid #333;
}
p {
max-width: 600px;
}
Output
<img style="float:left; margin-right:15px; width:150px; height:100px; border:2px solid #333;" src="https://via.placeholder.com/150x100" alt="Placeholder Image"><p>This is a paragraph of text that wraps around the floated image on the left side. The float property allows the image to sit beside this text, creating a nice layout effect often used in articles and blogs.</p>
Common Pitfalls
When using float, the container may collapse because floated elements are removed from normal flow. This causes layout issues like zero height containers.
To fix this, use a clearfix or set overflow: auto; on the container.
css
/* Wrong: container collapses */ .container { border: 1px solid #ccc; } .floated { float: left; width: 100px; height: 100px; background: lightblue; } /* Right: clearfix applied */ .container::after { content: ""; display: block; clear: both; } /* Or alternative fix */ .container { overflow: auto; }
Quick Reference
| Property | Values | Description |
|---|---|---|
| float | left | Floats element to the left, allowing content to wrap on the right |
| float | right | Floats element to the right, allowing content to wrap on the left |
| float | none | Default; element does not float |
| clear | left | Prevents elements from wrapping on the left side |
| clear | right | Prevents elements from wrapping on the right side |
| clear | both | Prevents elements from wrapping on both sides |
Key Takeaways
Use
float: left or float: right to position elements side by side with text wrapping.Floated elements are removed from normal flow, so their container may collapse without clearfix or overflow fixes.
Use the
clear property to control where wrapping stops after floated elements.Avoid using float for complex layouts; modern CSS layout tools like Flexbox and Grid are better choices.
Always add margin to floated elements to separate them from surrounding content.