
Clearfix hack
If we look at the following CSS, right below our reset, these rulesets make up our clearfix:
/* clearfix */ .grouping:before, .grouping:after { content: " "; display: table; }
.grouping:after {
clear: both;
}
This code was actually part of our base layer of CSS. Basically, what this does is create a pseudo element before and after any element with a class of grouping. This pseudo element has a blank space for content and the display is set to table. Then we have the after pseudo element beneath that chunk of code, which has the clear property set on it and clears any floats before it.
You might sometimes see clearfix as the class name instead of grouping. I tend to use grouping because I think it makes more sense; you're kind of grouping elements, and that's a little bit more semantic. It doesn't really matter though; clearfix and grouping both do the same thing.
All right, that's already in the CSS, so there's nothing more we need to do except go to secondary-section in the HTML and just add this grouping class to it. So we're adding a second class to it:
<section class="secondary-section grouping">
When we save and refresh, we have our container; the collapse is fixed. In the next screenshot, we see the background color and the bottom margin. We're in pretty good shape here:

The clearfix will work in IE8 but not IE7 unless you add an IE-specific style sheet. This actually goes in the index. So up in the head of index.html, I have this style sheet, shown in the next screenshot, specifically for IE7. What it does is give grouping a zoom of 1. This triggers something called hasLayout in older versions of IE, which clears the collapse:

Don't worry if that doesn't make too much sense to you; it doesn't necessarily have to. However, just know that this allows the clearfix hack to work in older versions of IE. So, all in all, this is very deep browser support, and it's so very easy to use that it's many frontend developers' preferred way of clearing collapsed floats. It's certainly my favorite way of going about it.
In this section, you learned about fixing the collapse of parent elements caused by floats using:
- An empty clear div.
- The overflow: hidden.
- By floating the parent element. All three of these worked but had minor to major flaws.
- The clearfix hack with very deep support, ease of use, and semantic style tends to win as the best method. I use it on every project. It can easily solve one of the biggest problems with floats: collapse. Another thing I like about the clearfix hack is that it is a very modular approach to CSS. Just add the clearfix class anywhere to your markup and you've gotten rid of collapsed containers.