萬盛學電腦網

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

CSS 清除浮動終極方案:Micro Clearfix 相容所有主流瀏覽器

經典 Clearfix(Nicolas Gallagher 改良版)

.clearfix::before,
.clearfix::after {
  content: "";
  display: table;
}
.clearfix::after { clear: both; }
.clearfix { *zoom: 1; } /* IE 6/7 觸發 hasLayout */
標準 Clearfix 代碼

精簡版(僅支援現代瀏覽器 + IE8+)

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
.clearfix { *zoom: 1; }
精簡 Clearfix 代碼

原理解析

  • ::before 修正 margin-top 塌陷(現代瀏覽器)。
  • ::after + clear:both 清除浮動,撐開父層高度。
  • *zoom:1 觸發 IE6/7 hasLayout,達到同樣清除效果。

其他常見清除浮動方法比較

方法優點缺點
額外空 <div style="clear:both"></div>簡單直觀污染 HTML 結構、無語意
父層 overflow:hidden/auto無額外標籤可能裁切陰影/絕對定位子元素、觸發滾動條
父層 display:flow-root現代標準、語意清晰IE/Edge 舊版不支援
父層 float:left/right自動包含浮動子元素父層本身脫離文件流,影響佈局

最佳實踐建議

  • 專案統一採用 .clearfix 類別,語意明確、可複用。
  • 現代專案(不支援 IE)直接用 display: flow-root。
  • 避免濫用 overflow:hidden 清除浮動,防止副作用(參見 overflow 陷阱)。
copyright © 萬盛學電腦網 all rights reserved