QQ截图20170527164120.png
<div>
<div style="float:left;width:200px;height:200px;background:red;"></div>
<div style="float:left;width:200px;height:200px;background:blue;"></div>
<div style="float:left;width:200px;height:200px;background:orange;"></div>
<div style="float:left;width:200px;height:200px;background:yellow;"></div>
</div>
以上的代码中,我们定义了四个背景颜色不一致,大小一致的盒子,并对每个盒子设置了左浮动,四个盒子被包裹在div
盒子中。
chrome开发者工具中,我们看到外层盒子的高度变成了0。内部盒子的高度是200px,正常情况下,父元素的高度是子元素的高度。
这里因为给四个盒子设置了浮动,引起了高度塌陷。当没有高度的父级盒子里的元素设置了浮动的时候。父元素中内部高度因为是普通流中的块元素撑起来的,所以这个时候父元素的高度会变成0,或者会有部分浮动元素的位置会超出父元素的高度之外。这种现象,叫做高度塌陷。
解决方法:
- 父级元素设置overflow:hidden;或者position:absolute或者position: fixed;
2.清除浮动:父级元素添加clearfix
.clearfix{*zoom:1}
.clearfix:after{
content:"\0020";
display:block;
clear:both;
width:0;
height:0;
}