这个看上去又简单又实用,但是你不能对父级 div 设置高度,一旦父级 div 设置了固定高度,那么浮动元素超出的部分也会被隐藏。
复制代码
<style>
#a {
width: 100px;
height: 20px;
border: 1px solid #ccc;
overflow: hidden;
}
#b {
height: 50px;
float: left;
border: 1px solid #ccc;
}
</style>
<div id=”a”>A
<div id=”b”>B</div>
</div>

当使用 overflow: auto 属性同时设定固定高度时效果为:

设置父级 div 伪类 before && after
这个方法即问题中介绍的新方法,对父级 div 设置伪类 before 和 after 的值。
复制代码
<style>
#a {
width: 100px;
border: 1px solid #ccc;
}
#a:before, #a:after {
content: “”;
display: block;
clear: both;
height: 0;
visibility: hidden;
}
#b {
height: 50px;
float: left;
border: 1px solid #ccc;
}
</style>
<div id=”a”>A
<div id=”b”>B</div>
</div>

这个方法应该是最佳方案,即不会产生无意义的空 div,同时当父级元素高度固定时并不会影响内部的浮动元素高度。但是唯一一点就是伪类的兼容性问题。对于低版本的 IE 浏览器我们可以使用:
复制代码
#a {
zoom:1
}
在阅读了 @ShingChi 兄推荐的这篇博文 – http://nicolasgallagher.com/micro-clearfix-hack/ 后,我们还可以进一步地简化代码如下:
复制代码
<style>
#a {
width: 100px;
border: 1px solid #ccc;
}
#a:before, #a:after {
content: “”;
display: table;
clear: both;
}
#b {
height: 50px;
float: left;
border: 1px solid #ccc;
}
</style>
<div id=”a”>A
<div id=”b”>B</div>
</div>










