为什么要清除浮动?
首先看一下下面这个布局
<style>
.fatherBox{
width: 800px;
border: 1px solid red;
margin: 0 auto;
}
.first{
width: 200px;
height: 150px;
background-color: blue;
}
.second{
width: 300px;
height: 200px;
background-color: yellow;
}
.third{
width: 150px;
height: 100px;
background-color: green;
}
</style>
<div class="fatherBox">
<div class="first">first</div>
<div class="second">second</div>
<div class="third">third</div>
</div>
父盒子没有设置高度,它随着子盒子的添加而改变,但是我想用浮动float让这三个盒子在一行显示,为这三个子盒子添加float: left
属性
可以发现,虽然这三个子盒子在一行显示了,但是父盒子的高度不对了,如果这时候父盒子后面还有一个盒子
.fatherBox2{
width: 800px;
height: 300px;
margin: 0 auto;
background-color: aqua;
}
<div class="fatherBox2"></div>
就会变成这样
清除浮动的原因:父级盒子在很多情况下不适合设置固定的高度,需要根据子盒子来变化,但是子盒子浮动又不占有位置,所以父盒子的高度会变成0,因此会影响后面的标准流盒子,对后面的排版产生影响,这就需要清除浮动(本质是清除浮动元素造成的影响)
清除浮动有以下几种方式
1、额外标签法(隔墙法)
这种方法不常用
语法
选择器:{clear: 属性值;}
属性值 | 描述 |
---|---|
left | 不允许左侧有浮动元素(清除左侧浮动的影响) |
righr | 不允许右侧有浮动元素(清除右侧浮动的影响) |
both | 同时清除左右两侧浮动的影响 |
实际上几乎只用clear:both
.clear{
clear: both;
}
<div class="fatherBox">
<div class="first">first</div>
<div class="second">second</div>
<div class="third">third</div>
<div class="clear"></div><!-- 额外添加的标签 -->
</div>
<div class="fatherBox2"></div>
优点:书写简单,通俗易懂
缺点:需要添加无意义的标签,结构化较差
2、父级添加overflow属性
可以给父级添加overflow属性,将属性值设置为hidden,auto或scroll
.fatherBox{
overflow: hidden;/* 添加overflow属性 */
width: 800px;
border: 1px solid red;
margin: 0 auto;
}
优点:代码简洁
缺点:无法显示溢出的部分(如果子元素宽度超过父元素的宽度将不会显示超过的部分)
3、父级添加after伪元素
:after是额外标签法的升级版,在整个父盒子后面添加一个块元素,这个块有clear:both属性,因此可以清除浮动
.clearfix:after{
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix{
*zoom: 1;/* 兼容ie6、7 */
}
<div class="fatherBox clearfix"><!-- 添加clearfix类 -->
<div class="first">first</div>
<div class="second">second</div>
<div class="third">third</div>
</div>
<div class="fatherBox2"></div>
优点:没有增加标签,结构简单清晰
缺点:需要兼容低版本的浏览器
4、父级添加双伪元素
.clearfix:before,.clearfix:after{
content: "";
display: table;
}
.clearfix:after{
clear: both;
}
.clearfix{
*zoom: 1;/* 兼容ie6、7 */
}
<div class="fatherBox clearfix"><!-- 添加clearfix类 -->
<div class="first">first</div>
<div class="second">second</div>
<div class="third">third</div>
</div>
<div class="fatherBox2"></div>
优点:代码更简洁
缺点:需兼容低版本浏览器