使用 CSS 清除修复和展开边距而不产生副作用?

Qta*_*tax 3 css margin css-float

使用 CSS 清除固定和展开边距而不产生副作用(也没有额外的 HTML 元素)的一般好方法是什么?

以下因素会导致副作用(并且希望避免它们):

  • 设置overflow: hiddenoverflow: auto:剪辑box-shadow、CSS 转换以及人们可能希望在框外显示的其他内容。因此它不能在多种情况下使用(但在其他方面效果很好)。
  • 设置borderpadding:明显的定位/尺寸效果。

Qta*_*tax 5

清除和折叠修复,基于此清除修复,并添加了边距展开:

.group:before, /* :before to uncollapse the top margin */
.group:after{
    display: block;
    clear: both; /* clear fix */
    content: "\a0 "; /*   - just a space doesn't uncollapse margins */
    visibility: hidden; /* make sure not to show anything */
    height: 0;
}
.group{
    zoom: 1; /* solves it all for IE < 8, and doesn't hurt other browsers */
}
Run Code Online (Sandbox Code Playgroud)

演示jsFiddleIE7 使用 netrenderer 渲染

请注意,content: "\a0 ";相当于&nbsp;和 ,而不是非空白字符(例如.),这样当您选择块并复制它时,您不会获得额外的可见字符,否则在某些浏览器(例如 IE9)中会发生这种情况。

该解决方案的缺点是:

  • :before:after已被定义,因此使用它们时需要特别小心。
  • 对于您想要应用此修复的每个新选择器,您必须指定该选择器 3 次。
  • 不是很短/琐碎。

YUI使用了类似的解决方案,如本文所述(但没有&nbsp;)。

  • 这种clearfix技术需要更少的CSS:http://nicolasgallagher.com/micro-clearfix-hack/ (2认同)