清除浮动的方法

清除浮动带来的影响

浮动造成父元素高度塌陷

清除浮动的方法

  • 底部插入有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不能“一方通行”

权衡后的策略

// 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只需要应用到包含浮动子元素的父元素上,切勿滥用

原文地址:https://www.cnblogs.com/White-Quality/p/10114610.html