The legacy CSS float property pushes an element to the left or right of its container, allowing text and inline elements to wrap around it. clear prevents elements from floating alongside preceding floated elements.
Float pushes elements horizontally:
.img-float-left { float: left; margin-right: 15px; }
.img-float-right { float: right; margin-left: 15px; }
/* Clear float wrap */
.clear-both { clear: both; }
/* Modern Clearfix Hack */
.clearfix::after {
content: "";
display: table;
clear: both;
}
Float mechanics explained:
float: left / right: Shifts elements to the left or right edge of their parent container.flowchart LR
A["Float Element (float: left)"] --> B["Paragraph Text Paragraph Text Paragraph Text Wraps Right"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Float Demonstration</title>
<style>
.article-card {
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
max-width: 550px;
}
/* Clearfix hack */
.article-card::after {
content: "";
display: table;
clear: both;
}
.float-thumb {
float: left;
width: 120px;
height: 90px;
object-fit: cover;
border-radius: 6px;
margin-right: 1rem;
margin-bottom: 0.5rem;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<div class="article-card">
<img src="https://images.unsplash.com/photo-1518770660439-4636190af475" alt="Thumbnail" class="float-thumb">
<h3>Article Title with Floated Image</h3>
<p style="color: #94a3b8; margin: 0;">This paragraph text flows smoothly around the left-floated image thumbnail inside the container box.</p>
</div>
</body>
</html>
float primarily for text wrapping around article images: Reserve float for inline editorial article imagery wrapping.float: Avoid building multi-column page layouts with float; use Flexbox or CSS Grid.Create a .clearfix::after rule setting content: ""; display: table; clear: both;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.