产生浮动的原因
设计时使用浮动的方式进行布局,会使元素脱离文档流,在文档流中,父元素会默认被子元素撑开,一旦子元素设置浮动,就会脱离文档流,导致子元素无法撑起父元素的高度,这就是高度塌陷问题。
清除浮动的目的
为了自适应,父盒子是不设置高度的,其块级元素为了在同一行显示,就会让块级元素设置float浮动,这时候子元素就脱离了标准流,而父盒子没有脱离标准流。
不清除浮动的情况显示
<style>
.main {
width: 500px;
height: 300px;
border: 1px solid red;
margin: 150px auto;
}
.father-box {
width: 300px;
}
.son-one {
width: 100px;
height: 100px;
float: left;
background-color: rosybrown;
}
.son-two {
width: 100px;
height: 100px;
float: left;
background-color: sandybrown;
}
.bottom-box {
width: 300px;
height: 50px;
background-color: skyblue;
text-align: right;
}
</style>
<body>
<div class="main">
<div class="father-box">
<div class="son-one">A的子元素1</div>
<div class="son-two">A的子元素2</div>
</div>
<div class="bottom-box">同级盒子B</div>
</div>
</body>
浮动带来的缺陷
由于设置了float后元素脱离了标准流,从而导致了高度的塌陷,例子如下
当出现高度塌陷后原本想放在下面的元素会自动向上补充。
解决方案
- 浮动高度确定的情况下,给父盒子添加高度
.father-box {
width:300px;
height:100px;
}
- 父盒子添加overflow:auto/overflow:hidden
.father-box{
width:300px;
overflow:auto
}
缺点:内容增多的时候容易造成不会自动换行导致内容被隐藏掉,无法显示要溢出的元素。
- 使用after伪元素清除浮动(推荐)
<style>
.clearfix::after{
content:'';
clear:both;
display:block;
visibility:hidden;
}
</style>
<body>
<div class="main">
<div class="father-box clearfix">
<div class="son-one">A的子元素1</div>
<div class="son-two">A的子元素2</div>
</div>
<div class="bottom-box">同级盒子B</div>
</div>
</body>
- 使用双伪元素清除浮动(推荐)
<style>
.clearfix::after,.clearfix::before {
content:'';
display:table;
}
.clearfix::after {
clear:both;
}
.clearfix {
*zoom:1;
}
</style>
<body>
<div class="main">
<div class="father-box clearfix">
<div class="son-one">A的子元素1</div>
<div class="son-two">A的子元素2</div>
</div>
<div class="bottom-box">同级盒子B</div>
</div>
</body>