Clearing Floats
Learn how to clear floats and fix the container collapse problem using clear, overflow, and clearfix techniques.
Clearing Floats
In the previous episode, we saw that floated elements cause their parent container to collapse. Let's learn three techniques to fix this.
The Problem
<div class="container" style="background: #eee; border: 2px solid #333;">
<div style="float: left; width: 100px; height: 100px; background: #6c5ce7;"></div>
<div style="float: left; width: 100px; height: 100px; background: #a78bfa;"></div>
</div>
<p>This paragraph appears right after the container.</p>
The container has zero height because both children are floated. The paragraph appears behind the floated boxes.
Solution 1: The clear Property
The clear property tells an element: "don't allow floated elements on my specified side."
| Value | Behavior |
|---|---|
clear: left; | Don't allow left-floated elements to my left |
clear: right; | Don't allow right-floated elements to my right |
clear: both; | Don't allow floated elements on either side |
<div class="container">
<div style="float: left;">Floated</div>
<div style="clear: both;"></div> <!-- Clears the float -->
</div>
Solution 2: overflow: hidden
Adding overflow: hidden (or overflow: auto) to the parent creates a new Block Formatting Context (BFC), which forces it to contain its floated children:
.container {
overflow: hidden; /* or overflow: auto */
background: #eee;
border: 2px solid #333;
}
This is simple and effective, but be careful — it will clip any content that overflows the container.
Solution 3: The Clearfix Hack (Best Practice)
The most reliable solution is the clearfix — a pseudo-element that clears floats automatically:
.clearfix::after {
content: "";
display: table;
clear: both;
}
Apply the class to any container with floated children:
<div class="container clearfix">
<div style="float: left;">Floated 1</div>
<div style="float: left;">Floated 2</div>
</div>
<!-- Container now wraps its children properly -->
Comparison of Solutions
| Method | Pros | Cons |
|---|---|---|
clear: both div | Simple | Adds extra HTML markup |
overflow: hidden | No extra markup | May clip overflowing content |
| Clearfix ::after | Clean, reusable, no side effects | Need to remember to apply the class |
Modern Alternative: display: flow-root
The modern CSS way to create a BFC is display: flow-root:
.container {
display: flow-root;
}
This is the cleanest solution, but it's newer and may not be supported in very old browsers.
Key Takeaways
- Floated children cause parent containers to collapse
- Use
clear: bothto prevent elements from sitting beside floats - Use
overflow: hiddenon the parent for a quick fix - The clearfix pseudo-element (
::after) is the classic best practice display: flow-rootis the modern, clean solution