清除浮動的方法

清除浮動帶來的影響

浮動形成父元素高度塌陷code

清除浮動的方法

  • 底部插入有clear:both;的元素
  • 父元素BFC(IE8+)或haslayout(IE6/IE7)

清除浮動方法的差別

clear:both

  1. 與外界接觸
  2. margin重疊

BFC/haslayout

  1. 封閉結構,內部聲明不會對外部形成任何影響

clear一般應用形式

clear:both

  • HTML block水平元素底部走起
<div ...></div>
  • Css after 僞元素底部生成
.clearfix:after{}

兩種形式的不足

  • div元素--不少裸露的div標籤
  • after僞元素--不兼容IE6/IE7

BFC/haslayout一般聲明

  • float:left/right
  • position:absolute/fixed
  • overflow:hidden/scroll(IE7+)
  • display:inline-block/table-cell(IE8+)
  • width/height/zoom:1/...(IE6/IE7)

因BFC不能「一方通行」it

權衡後的策略

// IE8+
.clearfix:after{
    content:'';
    display:block;
    height:0;
    overflow:hidden;
    clear:both;
}
// IE6/IE7
.clearfix{
    *zoom:1;
}

更好的方法

// IE8+
.clearfix:after{
    content:'';
    display:table;
    clear:both;
}
// IE6/IE7
.clearfix{
    *zoom:1;
}

.clearfix只須要應用到包含浮動子元素的父元素上,切勿濫用io

相關文章
相關標籤/搜索