CSS 清除浮动



清除浮动是一种技术,用于确保容器正确包含其内的浮动元素(例如图像)。它通过向容器添加一个空元素来防止布局问题,该元素清除左右两侧的浮动。

左浮动
右浮动
后续内容

清除浮动的工作原理?

要理解清除浮动的工作原理,首先您需要了解 **float** 属性和浮动元素。在 CSS 中,浮动元素是从正常文档流中移除并放置在其包含块的左侧或右侧的元素。例如,有时图像元素会放置在容器元素的右侧,文本会环绕它。

由于浮动元素已从正常的文档流中移除,父容器可能会折叠并且无法包含浮动的子元素。因此,使用清除浮动技术可确保父元素正确地环绕浮动元素。以下是清除浮动的基本 CSS 代码

.clearfix::after { content: ""; display: table; clear: both; }

以上语法遵循以下规则。

  • content: "" 用于生成伪元素。
  • display: table 使伪元素成为块级元素,并确保它占据父元素的全部宽度。
  • clear: both 清除两侧(左侧和右侧)的浮动。

清除浮动有助于防止容器折叠、高度不一致、内容重叠、对齐不一致等问题。

CSS 清除浮动的示例

以下 HTML 代码展示了如何使用清除浮动来防止容器折叠。

示例

Open Compiler
<!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>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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

使用 overflow 属性的 CSS 清除浮动

我们还可以使用 CSS 中的 **overflow** 属性实现与清除浮动类似的功能。`overflow: auto;` 将使容器延伸以适应所有内部元素。

不建议使用此方法。只要能够控制页边距和内边距(否则可能会看到滚动条),`overflow:auto` 清除浮动效果很好。

示例

Open Compiler
<!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>
广告