什么是clearfix (一文搞清楚css清除浮动clearfix)

CSS教程 2025-08-26

目录

  • 什么是 clearfix ?
  • 自清除子元素浮动
  • Margin Collapse 外边距重叠问题
  • 结语

什么是 clearfix ?

clearfix 是一种 CSS 技巧,可以在不添加新的 html 标签的前提下,解决让父元素包含浮动的子元素的问题。这个技巧的版本是很多的,最流行的一个是 Micro Clearfix Hack 。这个也是 Bootstrap 采用的方案(可以 google 一下 bootstrap clearfix 来查看详情)。

Micro Clearfix Hack 的作者给出的原始方案,内容如下:

/**
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    contenteditable attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that are clearfixed.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */
.cf:before,
.cf:after {
    content:  ; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.cf {
    *zoom: 1;
}

但是我的习惯是支持到 IE9+ ,同时习惯了用 clearfix 作为 class 名,所有稍微修改后的版本如下:

.clearfix:before,
.clearfix:after {
    content:  ;
    display: table;
}

.clearfix:after {
    clear: both;
}

百度用的代码

.clearfix:after{content:'20';display:block;height:0;clear:both}
.clearfix{zoom:1}
.clear{clear:both;height:0;line-height:0;font-size:0;visibility:hidden;overflow:hidden}

本站用的

.clear{clear: both;overflow: hidden;line-height: 0;height: 0;zoom:1}
.clear:after {display: block; height: 0px; visibility: hidden; clear: both; content: }
.clearfix{ *zoom:1;}
.clearfix:before,	
.clearfix:after {content: .;display: block;height: 0;overflow: hidden;visibility: hidden;}
.clearfix:after{clear: both}

用了这个方法很长时间之后,都觉得上面的代码就是天书,尤其是对 display: table 这一行不理解。其实,这些代码为的是解决两个实际中经常遇到,而且非常让人恼火的问题。问题搞清楚了,代码也就明白了。

自清除子元素浮动

  • 先说第一个问题和解决方案。

  • div 布局的一个非常让新手头疼的问题就是,如果一个父元素中包含若干个子元素,那么当给所有的子元素都设置了浮动( e.g float: left ),那么父元素的高度就会为0。

比如有这样的 html 代码:

div class=container
  div class=item1/div
  div class=item2/div
/div

如果子元素没有浮动,那么显示是这样的:

这里写图片描述

结语

上面两个问题的解决代码合并到一起,就是文章最初 Peter 给出的 clearfix 代码了。 有了这个方法,当给子元素添加浮动或者是 margin 的时候,父元素的行为就非常符合正常的预期了,开发页面布局变得非常简单,所以 clearfix 方法对于按照 div 的 block 模型排版是非常有用的。

下面分享一段当前比较常用的代码

.clearfix:after{content:'20';display:block;height:0;clear:both}
.clearfix{zoom:1}
.clear{clear:both;height:0;line-height:0;font-size:0;visibility:hidden;overflow:hidden}

但是,顺便提一下,未来 flexbox 会大行其道,flexbox 模型的特点是,不用 float ,并且子元素的 margin 也不会和父元素重叠。

到此这篇关于什么是clearfix (一文搞清楚css清除浮动clearfix)的文章就介绍到这了,更多相关什么是clearfix内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!