译:能够用什么方法清除浮动?

原文连接:http://stackoverflow.com/a/1633170css

根据正在生产中的设计,如下每一个 clearfix CSS 解决方案都有本身的优点。html


“Reloaded" clearfix

CSS Mojo 的 Thierry Koblentz' 写了另外一篇文章来从新审视清除浮动,强有力地证实了使用 display: block 不会禁用外边距重叠,这比使用 display: table 更有优点。浏览器

最新的 micro-clearfix 代码:ui

.container::after {
  content: ""; /* If you do not care for “old” Opera */
  display: block;
  clear: both;
}

(译注:若是要支持老 Opera 浏览器,应使用 content: " ")编码

“Best That ClearFix",一个为现代浏览器而生的 clearfix

CSS Mojo 的 Thierry Koblentz' 指出当编码目标为现代浏览器时,咱们能够放心的移除 zoom::before 属性/值转而简单地使用:.net

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

这种方式不支持 IE6/7设计

Thierry 指出:“谨慎提醒:若是你要从头开始一个新项目,去吧!可是不要切换你如今使用的技术,由于即使你如今不打算支持老 IE 浏览器,你如今的规则仍能防止外边距重叠。”code

Micro Clearfix

最新的全球都采用的 clearfix 解决方案,Micro Clearfix by Nicolas Gallagher.htm

.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container {
  zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

溢出属性

当定位内容不会超出容器的边距时,一般状况下该方法是优先选择的。element

http://www.quirksmode.org/css/clearing.html - 阐述如何解决与此技术有关的常见问题,即,在容器上设置 width: 100%.

.container {
  overflow: hidden;
  display: inline-block; /* Necessary to trigger "hasLayout" in IE */
  display: block; /* Sets element back to block */
}

除了使用 display 属性来为 IE 触发 "hasLayout",其它属性也能够在元素上触发 IE 的 "hasLayout".

.container {
  overflow: hidden; /* Clearfix! */
  zoom: 1; /* Triggering "hasLayout" in IE */
  display: block; /* Element must be a block to wrap around contents. Unnecessary if only using block-level elements. */
}

另外一种使用 overflow 属性清除浮动的方式是用 underscore hack. IE 将会应用前置下划线属性的值,其它浏览器不会。zoom 属性将会在 IE 中触发 hasLayout:

.container {
  overflow: hidden;
  _overflow: visible; /* for IE */
  _zoom: 1; /* for IE */
}

虽然能够工做,但使用 hack 并不是理想的选择。

"::after" 伪元素

这种老的“简明清除”方法有容许定位元素悬挂在容器以外的优势,可是以付出更多棘手的 CSS 为代价的。

http://www.positioniseverything.net/easyclearing.html

.container {
  display: inline-block;
}
.container::after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  overflow: hidden;
  visibility: hidden;
}
.container {
  display: block;
}

除非你须要支持 IE 8,你应该老是对 beforeafter 使用双冒号 ::. 双冒号是伪元素的标准实现,而且再也不建议使用单冒号。将来可能放弃对单冒号的支持。

对元素使用"clear"属性

简明扼要的方法:

<br style="clear:both" /> <!-- So dirty! -->

不少缘由证实使用清除标签并不理想:

  • 主要缘由:你将样式带入到了标记中。这意味着若是你不想使用相同标记的文档,重用标记将会变得更加困难。应该使用 CSS 在不一样的上下文中对相同的标记进行格式化。
  • 不能为你的标签添加任何语义信息。
  • 使你的代码看起来不专业
  • 在将来你想使用其余的 clearfix 解决方案时,你将不得不回过头来删除全部的 <br> 标签。
相关文章
相关标签/搜索