萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS clearfix 清除浮動演進史:從空標籤到終極版雙偽元素方案

原始暴力法

.clear { clear: both; line-height: 0; }

缺點:每次清除需加空標籤,頁面結構汙染嚴重。

Clearfix 起源(支援 IE/Mac)

.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)。

IE6/7 簡化版

.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 同時生效 */

現代重構:Block Formatting Context (BFC)

建立 BFC 可閉合內部浮動。途徑:

  • float 不為 none
  • overflow 不為 visible
  • display 為 table-cell/table-caption/inline-block
  • position 為 absolute/fixed

float/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 清除浮動。代碼最精簡、語義最清晰,**目前主流最佳實踐**。

copyright © 萬盛學電腦網 all rights reserved