什么是float浮动,造成父级元素高度为0
一般而言,父级元素不设置高度时,高度由随内容增加自适应高度。当父级元素内部的子元素全部都设置浮动float之后,子元素会脱离标准流,不占位,父级元素检测不到子元素的高度,父级元素高度为0。
/*css样式*/
<style type="text/css">
.box{ background:skyblue; }
.kid{ width: 100px;height: 100px; float:left;}
.kid1{ background: yellow; }
.kid2{ background: orange; }
.wrap{ width: 300px; height: 150px; background: blue; color: white; }
</style>
/*html*/
<body>
<div class="box">
<div class="kid kid1">子元素1</div>
<div class="kid kid2">子元素2</div>
</div>
<div class="wrap">其他部分</div>
</body>
如上,由于父级元素没有高度,下面的元素会顶上去,造成页面的塌陷。因此,需要给父级加个overflow:hidden属性,这样父级的高度就随子级容器及子级内容的高度而自适应。如下:
/*css样式*/
<style type="text/css">
.box{ background:skyblue;
overflow: hidden; /*清除浮动*/
zoom:1;
}
.kid{ width: 100px;height: 100px; float:left;}
.kid1{ background: yellow; }
.kid2{ background: orange; }
.wrap{ width: 300px; height: 150px; background: blue; color: white; }
</style>
/*html*/
<body>
<div class="box">
<div class="kid kid1">子元素1</div>
<div class="kid kid2">子元素2</div>
</div>
<div class="wrap">其他部分</div>
</body>