Clearfix Techniques
What you'll learn: How to fix the problem where a container collapses when all its children are floated, making the container appear empty.
The Container Collapse Problem
When you float all the children inside a container, those floated elements are removed from normal flow. The parent container doesn't "see" them anymore and collapses to zero height (or just enough to contain any padding/borders). It's like the parent thinks the room is empty even though furniture is floating around inside it!
Solution 1: The Classic Clearfix
Add an invisible element after the floated children that uses clear: both. This forces the container to stretch down past the floats:
.container::after {
content: "";
display: block;
clear: both;
}
The ::after pseudo-element creates a clearing element without adding extra HTML. This is the modern "clearfix" pattern you'll see everywhere.
Solution 2: Overflow Method
Set overflow: auto (or overflow: hidden) on the parent container:
.container {
overflow: auto;
}
This creates a new block formatting context, which forces the container to contain its floated children. Think of it as telling the parent, "Yes, actually look inside and measure everything properly."
Which Should You Use?
The ::after clearfix is generally preferred because it's more explicit about why you're fixing the problem. The overflow method can sometimes hide content or add scrollbars unexpectedly.
Key Takeaway: When a container collapses because its children are floated, use either a clearfix with ::after and clear: both, or apply overflow: auto to the parent to restore proper containment.