本属于普通流中的元素浮动之后,包含框内部由于不存在其他普通流元素了,也就表现出高度为0(高度塌陷)。在实际布局中,往往这并不是我们所希望的,所以需要闭合浮动元素,使其包含框表现出正常的高度。 暴力的方法:
#main{
background-color: green;
}
.left{
background-color: red;
height: 500px;
width: 200px;
float: left;
}
.center{
background-color: blue;
display: table-cell;//形成BFC
width: 3000px
}
<div id="main">
<div class="left">左边</div>
<div class="center">中间</div>
<div style="clear:both"></div>//添加无意义的标签,不利于后期维护,不符合表现与结构分离
</div>
更好的方法:
#main{
background-color: green;
}
.left{
background-color: red;
height: 500px;
width: 200px;
float: left;
}
.center{
background-color: blue;
display: table-cell;
width: 3000px
}
.clearfix:after{
content: '';
display: table;
clear:both;
}
.clearfix{
*zoom:1;//激发hasLayout,兼容IE6/7
}
<div id="main" class="clearfix">
<div class="left">左边</div>
<div class="center">中间</div>
</div>
关于
.center{
background-color: blue;
display: table-cell;
width: 3000px
}
table-cell:单元格有个非常神奇的特性,就是你宽度值设置地再大,实际宽度也不会超过表格容器的宽度。
也可以改为overflow或display,但各有其缺点和优点。
overflow:auto/hidden IE7+,可能出现滚动条或内容被隐藏
display:inline-block IE6/IE7,内部元素的宽度决定了它的宽度
display:table-cell IE8+