The comment — and by extension, the code — that you've quoted is from the micro clearfix hack as proposed by Nicolas Gallagher, as mentioned in the top answer to that question. Nicolas wrote an article introducing the technique (which for some reason isn't linked to within the other answer), and in it he explains why display: table
is used, as follows:
This “micro clearfix” generates pseudo-elements and sets their display
to table
. This creates an anonymous table-cell 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.
In more detail, if an element has a first child and both of them are display: block
, and the child has a top margin, what happens is that the child margin will combine, or collapse, with the parent margin (if any), resulting in the top margin apparently disappearing from the child element, which can sometimes be undesirable. For an illustration of this effect, see this question.
Margins do not collapse through table elements for obvious reasons, which is why the display: table
hack works.
So, basically, the display: table
— and by extension, the :before
pseudo-element — is not essential to the clearfix, just an additional hack to block margins from collapsing between an element and its first child. If all you want to do is clear inner floats, which is what a clearfix is meant to do, then you don't need display: table
or :before
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…