更新:是的,链接的答案是坏的。我知道这一点,当我发布了这个答案,但我不觉得像复制和粘贴是OK的,由于版权,剽窃和你有什么。然而,我现在觉得好,因为我已经链接到原始文章。我还应该提及作者的名字,作为信用:Nicolas Gallagher。这里是文章的肉(注意,“Thierry的方法”是指Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
to table
. This creates an 07003 and a
new block formatting context that means the :before
pseudo-element
prevents top-margin collapse. The :after
pseudo-element is used to
clear the floats. As a result,there is no need to hide any generated
content and the total amount of code needed is reduced.
Including the :before
selector is not necessary to clear the
floats,but it prevents top-margins from collapsing in modern
browsers. This has two benefits:
-
It ensures visual consistency with other float containment techniques that create a new block formatting context,e.g.,
overflow:hidden
-
It ensures visual consistency with IE 6/7 when zoom:1
is applied.
N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context.
Further details can be found here: 07004.
The use of content:" "
(note the space in the content string) avoids
an 07005 that creates space around clearfixed elements if the
contenteditable
attribute is also present somewhere in the HTML.
Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is
to use font:0/0 a
.
Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the
addition of visibility:hidden
to hide the inserted character. This
is because legacy versions of Firefox need content:"."
to avoid
extra space appearing between the body
and its first child element,
in certain circumstances (e.g.,07006.)
Alternative float-containment methods that create a new block
formatting context,such as applying overflow:hidden
or
display:inline-block
to the container element,will also avoid this behaviour in legacy versions of Firefox.