float浮动是我们一定会的css知识点。但是float浮动会导致页面中某些元素不能正确的显示,那么我就需要清除浮动。
浮动影响:
1、由于浮动元素脱离了文档流,所以父元素的高度无法被撑开,影响了与父元素同级的元素;若没有给父元素设置高度,那么父元素就不会在显示屏上显示。
2、浮动元素不再占用原文档流的位置,它会对后面的元素排版产生影响。
清除浮动方法:
一、父级div定义 height(只适用于固定高度)
<style>
.div1{
background:#000;
border:1px solid red;
/*解决代码*/
height:200px;
}
.left{
float:left;
width:200px;
height:200px;
background:#666
}
</style>
<div class="div1">
<div class="left">Left</div>
</div>
⚠️ 固定高度! 固定高度! 固定高度!
二、使用clear:both清除浮动
<style>
.div1{
background:#000;
border:1px solid red;
}
.left{
float:left;
width:200px;
height:200px;
background:#666
}
</style>
<div class="div1">
<div class="left">Left</div>
<div style="clear: both"></div> <!-- 解决代码 -->
</div>
⚠️ 代码多余不利于维护
三、after伪元素
<style>
.div1{
background:#000;
border:1px solid red
}
.left{
float:left;
width:200px;
height:200px;
background:#666
}
/*解决代码*/
.clearfloat:after{
display:block;
clear:both;
content:"";
visibility:hidden
}
.clearfloat{
zoom:1 /*IE6、IE7.需要加*/
}
</style>
<div class="div1 clearfloat">
<div class="left">Left</div>
</div>
⚠️ ⚠️ ⚠️ 本人常用方法
据悉还有很多方法,就不一一列举,有兴趣的可以去了解一下
网友评论