官术网_书友最值得收藏!

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:

  1. An empty clear div.
  2. The overflow: hidden.
  3. By floating the parent element. All three of these worked but had minor to major flaws.
  4. 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.
主站蜘蛛池模板: 朝阳市| 襄城县| 日喀则市| 增城市| 沅江市| 盐源县| 资溪县| 东宁县| 天峻县| 鹿邑县| 永丰县| 故城县| 沾益县| 湘阴县| 和林格尔县| 栾城县| 屏边| 新田县| 南皮县| 社旗县| 康保县| 汝阳县| 永仁县| 疏勒县| 兰考县| 阜阳市| 揭阳市| 信阳市| 江陵县| 阆中市| 疏附县| 玉林市| 南木林县| 离岛区| 商都县| 晋州市| 米泉市| 南华县| 淮阳县| 崇礼县| 武强县|