清除浮动的几种方法
什么是浮动?
浮动是使用给节点添加float属性,最初的设计是用来实现文字环绕的。 添加了float的节点脱离文档流,同时触发节点的BFC,让节点往一个方向靠,并排成一行。
为什么要清除浮动?
一、兄弟级元素:
两个相邻的兄弟级元素,当前一个元素设置了浮动float时,后一位元素会移动到前一位元素的位置,被前一位元素遮挡。因此,为了解决这个问题,我们要为兄弟元素清除浮动。
兄弟级元素清除浮动 : clear:both;
<div class="bro1"></div>
<div class="bro2"></div>
<style>
.bro1{
width: 100px;
height: 100px;
background-color:green ;
/* 开启浮动 */
float: left;
}
.bro2{
width: 100px;
height: 100px;
background-color:orangered ;
/* 清除浮动 */
clear: both;
}
</style>
清除浮动前:清除浮动后:
二、父子级元素清除浮动:
当父元素未设置高度height,而子元素开启了浮动float,这时父元素会出现高度塌陷(高度为0)的问题。因此,为了解决这个问题,我们要为父元素清除浮动。
父元素设置高度:
<style>
/* 父元素样式 */
.father {
width: 400px;
height: 400px;
background-color: yellow;
}
/* 子元素样式 */
.child {
width: 200px;
height: 200px;
background-color: red;
/* 开启浮动 */
float: left;
}
</style>
<div class="father">
<div class="child"></div>
</div>
未出现高度塌陷时:子元素-红色、父元素-黄色
父元素没有设置高度,出现高度塌陷问题:
<style>
/* 父元素样式 */
.father {
width: 400px;
/* 去除高度 */
/*height: 400px;*/
background-color: yellow;
}
/* 子元素样式 */
.child {
width: 200px;
height: 200px;
background-color: red;
/* 开启浮动 */
float: left;
}
</style>
<div class="father">
<div class="child"></div>
</div>
出现高度塌陷:子元素-红色
父子级元素清除浮动:
1.额外标签法:给父元素添加一个额外的空白标签,再给这个标签设置clear:borh;
<style>
/* 父元素样式 */
.father {
width: 400px;
background-color: yellow;
}
/* 子元素样式 */
.child {
width: 200px;
height: 200px;
background-color: red;
/* 开启浮动 */
float: left;
}
.ww{
/* 清除浮动 */
clear: both;
}
</style>
<div class="father">
<div class="child"></div>
<div class="ww"></div>
</div>
2.给父元素添加overflow: 任意值;--可以通过触发BFC的方式,实现清楚浮动效果。
<style>
/* 父元素样式 */
.father {
width: 400px;
background-color: yellow;
/* 清除浮动 */
overflow: hidden;
/* overflow: scroll; */
/* overflow: auto; */
}
/* 子元素样式 */
.child {
width: 200px;
height: 200px;
background-color: red;
/* 开启浮动 */
float: left;
}
</style>
<div class="father">
<div class="child"></div>
</div>
3.使用::after伪元素清除浮动
<style>
/* 父元素样式 */
.father {
width: 400px;
background-color: yellow;
}
.father::after{
content: '';
display: block;
clear: both;
height: 0;
visibility: hidden;
}
/* 子元素样式 */
.child {
width: 200px;
height: 200px;
background-color: red;
/* 开启浮动 */
float: left;
}
</style>
<div class="father">
<div class="child"></div>
</div>
4.使用::before和::after双伪元素清除浮动
<style>
.father::before,.father::after{
content: '';
display: table;
}
.father::after{
clear: both;
}
</style>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。