使用before 和 after 伪元素清除浮动
时间: 2023-06-01 19:03:53 浏览: 137
在CSS中,使用before和after伪元素来清除浮动非常常见。以下是一个示例:
HTML代码:
```
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
```
CSS代码:
```
.parent:after {
content: "";
display: table;
clear: both;
}
.child {
float: left;
width: 33.33%;
}
```
在这个例子中,我们使用了after伪元素来清除浮动。我们设置content属性为空字符串,使其显示在元素的末尾。我们还将display属性设置为table,这样它就会占用整个父元素的宽度。最后,我们设置clear属性为both,这样它就会清除左右两侧的浮动效果。
您还可以使用before伪元素来清除浮动。在这种情况下,您只需要将伪元素添加到父元素之前即可。例如:
```
.parent:before,
.parent:after {
content: "";
display: table;
}
.parent:after {
clear: both;
}
.child {
float: left;
width: 33.33%;
}
```
在这个例子中,我们使用了before和after伪元素来清除浮动。我们将content和display属性分别设置为相同的值,并将before伪元素添加到父元素之前。我们还将clear属性设置为both,并将其添加到after伪元素中。
阅读全文
相关推荐
















