.clear { clear: both; line-height: 0; }
缺點:每次清除需加空標籤,頁面結構汙染嚴重。
.clearfix:after {
visibility: hidden; display: block; font-size: 0;
content: " "; clear: both; height: 0;
}
.clearfix { display: inline-table; } /* IE/Mac */
* html .clearfix { height: 1%; } /* IE6 hasLayout */
.clearfix { display: block; } /* 結束 IE/Mac hack */
複雜原因:早期瀏覽器差異極大(含 Mac IE5)。
.clearfix:after {
visibility: hidden; display: block; font-size: 0;
content: " "; clear: both; height: 0;
}
* html .clearfix { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */
IE6/7 不支援 :after,靠 zoom:1 觸發 hasLayout 清除浮動。IE8+ 已支援偽元素。
.clearfix:after {
visibility: hidden; display: block; font-size: 0;
content: " "; clear: both; height: 0;
}
.clearfix { *zoom: 1; } /* 針對 IE6/7 同時生效 */
建立 BFC 可閉合內部浮動。途徑:
float 不為 noneoverflow 不為 visibledisplay 為 table-cell/table-caption/inline-blockposition 為 absolute/fixedfloat/position 破壞佈局;overflow:hidden 會剪裁下拉選單;inline-block 產生空白節點。
→ **display: table 最佳**:匿名盒子產生 table-cell 形成 BFC,完美閉合浮動。
.clearfix:after {
content: "\200B"; /* Unicode 零寬空格 U+200B */
display: block; height: 0; clear: both;
}
.clearfix { *zoom: 1; }
省去 visibility:hidden,碼更精簡。
.clearfix:before, .clearfix:after {
content: ""; display: table;
}
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }
:before 防止頂部 margin collapse,:after 清除浮動。代碼最精簡、語義最清晰,**目前主流最佳實踐**。