目录
前言
为什么需要清除浮动?因为会存在以下情况:当父节点不设置高度时,子节点设置高度且设置浮动,脱离了标准流,此时父节点会高度塌陷。影响布局
如图:
正常状态下父节点未设置高度,子节点撑起了父节点
给子节点设置浮动后
.parent {
width: 150px;
border: 1px solid red;
}
.son {
width: 100px;
height: 100px;
background-color: orange;
float: left;
}
一、设置父节点高度
直接给父节点一个高度,优点是简单方便,但缺点是有时候节点无固定高度。
给父节点设置高度为120px
.parent {
width: 150px;
border: 1px solid red;
height: 120px;
}
.son {
width: 100px;
height: 100px;
background-color: orange;
float: left;
}
二、给父节点加overflow:hidden
.parent {
width: 150px;
border: 1px solid red;
overflow: hidden;
}
.son {
width: 100px;
height: 100px;
background-color: orange;
float: left;
}
三、在浮动元素后添加一个clear:both的元素
clear 属性指定元素两侧不能出现浮动元素
.parent {
width: 150px;
border: 1px solid red;
}
.son {
width: 100px;
height: 100px;
background-color: orange;
float: left;
}
.clear {
clear: both;
}
<div class="parent">
<div class="son"></div>
<div class="clear"></div>
</div>
四、在父元素内添加伪元素::after
.parent {
width: 150px;
border: 1px solid red;
&::after {
display: block;
content: ''; //content 属性与 :before 及 :after 伪元素配合使用,来插入内容。
clear: both;
visibility: hidden; //会使对象看不见,但在网页中所占的空间仍然存在
}
}
.son {
width: 100px;
height: 100px;
background-color: orange;
float: left;
}
五、在父元素内添加双伪元素::after,::before
.parent {
width: 150px;
border: 1px solid red;
&::before,
&::after {
content: '';
display: table;
}
&::after {
clear: both;
}
}
.son {
width: 100px;
height: 100px;
background-color: orange;
float: left;
}
总结
以上五种方法则是清除浮动常见的方法