一.为什么要清除浮动?
这是没有设置浮动时的盒子,外面的父盒子加了border,没有设置高度,内部盒子自动撑开
当给内部两个盒子设置浮动后,里面盒子脱离了文档流,父盒子变成一条线,并且底部盒子挤压上来
二.解决方案
这里提供三种解决方案,前两种不推荐使用
1.额外标签法
设置额外标签,并样式设置为 clear:both
<div class="father">
<div class="box">big</div>
<div class="small">小盒子</div>
<div class="clear"></div> //设置额外标签
</div>
<div class="footer">底部盒子</div>
<style>
.father{
width: 400px;
border: 1px solid black;
}
.box{
width: 100px;
height: 100px;
background-color: pink;
float: left;
}
.small{
width: 50px;
height: 50px;
background-color: rgb(126, 119, 119);
float: left;
}
.footer{
width: 650px;
height: 60px;
background-color:black;
}
.clear{
clear: both;
}
</style>
缺点:添加了无意义标签,语义化比较差
2.父级元素加overflow:hidden
<div class="father">
<div class="box">big</div>
<div class="small">小盒子</div>
<!-- <div class="clear"></div> -->
</div>
<div class="footer">底部盒子</div>
<style>
.father{
width: 400px;
border: 1px solid black;
overflow: hidden; //清除浮动
}
.box{
width: 100px;
height: 100px;
background-color: pink;
float: left;
}
.small{
width: 50px;
height: 50px;
background-color: rgb(126, 119, 119);
float: left;
}
.footer{
width: 650px;
height: 60px;
background-color:black;
}
</style>
缺点:如果文本较长,超出部分会被隐藏,且不会换行
三.after伪元素清除浮动 推荐使用
<div class="father clear">
<div class="box">big</div>
<div class="small">小盒子</div>
<!-- <div class="clear"></div> -->
</div>
<div class="footer">底部盒子</div>
<style>
.father{
width: 400px;
border: 1px solid black;
}
.box{
width: 100px;
height: 100px;
background-color: pink;
float: left;
}
.small{
width: 50px;
height: 50px;
background-color: rgb(126, 119, 119);
float: left;
}
.footer{
width: 650px;
height: 60px;
background-color:black;
}
.clear::after{ //伪元素清除浮动
content: '';
display: block;
height: 0;
clear: both;
visibility: hidden;
}
</style>