清除浮动
场景:浮动元素会脱标,如果父级没有高度,子级无法撑开父级高度(可能导致页面布局错乱)
解决方法:清除浮动(清除浮动带来的影响)
场景搭建
<style>
.top {
margin: 10px auto;
width: 1200px;
/* height: 300px; */
background-color: pink;
}
.left {
float: left;
width: 200px;
height: 300px;
background-color: skyblue;
}
.right {
float: right;
width: 950px;
height: 300px;
background-color: orange;
}
.bottom {
height: 100px;
background-color: brown;
}
</style>
<div class="top">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="bottom"></div>
额外标签法
在父元素内容的最后添加一个块级元素,设置 CSS 属性 clear: both
<style>
.clearfix {
clear: both;
}
</style>
<div class="top">
<div class="left"></div>
<div class="right"></div>
<div class="clearfix"><div>
</div>
单伪元素法
- 准备 after 伪元素
<style>
.clearfix::after {
content: "";
display: block;
clear: both;
}
</style>
- 父级使用 clear
<div class="top clearfix">
双伪元素法
- 准备 after 和 before 伪元素
<style>
/* before 解决外边距塌陷问题 */
/* 双伪元素法 */
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
/* after 清除浮动 */
.clearfix::after {
clear: both;
}
</style>
- 父级使用 clear
<div class="top clearfix">
overfow法
<style>
.top {
margin: 10px auto;
width: 1200px;
/* height: 300px; */
background-color: pink;
overflow: hidden;
}
</style>