清除浮动解决方案,使用.clearfix类选择器

清除浮动解决方案,使用.clearfix类选择器

这个东西其实很简单

使用css

1
2
3
4
5
.clearfix::after {
display: block;
content: "";
clear: both;
}

直接把要清除浮动的添加clearfix就行了

演示

html

1
2
3
<div class="container">
<div class="floated">floated</div>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.clearfix::after {
display: block;
content: '';
clear: both;
}

div {
border: 1px dashed skyblue;
}
.container {
width: 200px;
background: rgb(83, 152, 197);
}
.floated {
height: 300px;
float: left;
background: rgb(224, 173, 107);
}

1564491264766

容器未被撑开

添加clearfix

1
2
3
<div class="container clearfix">
<div class="floated">floated</div>
</div>

1564491322032

容器被撑开,浮动清除

clearfix还可以加入flow-root属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.clearfix::after {
display: block;
content: "";
clear: both;
}
/* 如果浏览器支持 flow-root属性 */
@supports(display: flow-root) {
.clearfix::after {
display: none;
}
.clearfix {
display: flow-root
}

}

关于flow-root,我的这篇文章有讲解

# css

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×