CSS - Clearfix
Clearfix 是一种技术,用于确保容器正确包围并包含其中的浮动元素(例如图像)。它通过向容器添加一个清空的元素来清除左右两侧的浮动,从而防止布局问题。
左浮动
右浮动
后续内容
Clearfix 如何工作?
要理解 clearfix 的工作原理,首先需要了解 float 属性和浮动元素。在 CSS 中,浮动元素是从正常文档流中移除并定位在其包含块左侧或右侧的元素。例如,有时图像元素会被定位在容器元素的右侧,文本会环绕其周围。
由于浮动元素从正常文档流中移除,父容器可能会塌陷,无法包含浮动子元素。因此,使用 clearfix 技术来确保父元素正确包裹浮动元素。以下是 clearfix 的基本 CSS 代码:
.clearfix::after {
content: "";
display: table;
clear: both;
}
上述语法遵循以下规则。
- content: "" 用于生成一个伪元素。
- display: table 使伪元素成为块级元素,并确保它占据父元素的完整宽度。
- clear: both 清除两侧(左和右)的浮动。
Clearfix 有助于防止容器塌陷、不均匀高度、内容重叠、对齐不一致等问题。
CSS Clearfix 示例
以下 HTML 代码展示了如何使用 clearfix 来防止容器塌陷。
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 3px solid;
padding: 5px;
}
img {
float: right;
width: 150px;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
</style>
</head>
<body>
<h2>没有 Clearfix</h2>
<div>
<img src="/css/images/css.png">
This image is floated to the right. As the image is
taller than the container, it overflows to outside.
</div>
<h2 style="clear:right">使用 Clearfix</h2>
<div class="clearfix">
<img src="/css/images/css.png" >
Here we added clearfix class to the containing element,
to fix this problem.
</div>
</body>
</html>
使用 Overflow 属性实现 CSS Clearfix
我们也可以使用 CSS 中的 overflow 属性来实现类似于 clearfix 的功能。overflow: auto; 会使容器扩展以适应所有内部元素。
不推荐使用这种方法。overflow: auto clearfix 只要你能控制好 margin 和 padding 就工作良好(否则可能会出现滚动条)。
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 3px solid;
padding: 5px;
}
img {
float: right;
width: 150px;
border: 1px solid;
}
.clearfix {
overflow: auto;
}
</style>
</head>
<body>
<h2>Without Clearfix</h2>
<div>
<img src="/css/images/css.png">
This image is floated to the right. As the image is
taller than the container, it overflows to outside.
</div>
<h2 style="clear:right">With Clearfix</h2>
<div class="clearfix">
<img src="/css/images/css.png" >
Here we added clearfix class to the containing element,
to fix this problem.
</div>
</body>
</html>