.clearfix::before,
.clearfix::after {
content: "";
display: block;
clear: both;
}
I think the clearfix method above is both compact and safe. However, I realised that if this method is as good as I think, it should have been the most popular clearfix method, while actually it isn't widely used.
My question is: what potential problem can this clearfix bring?
Here is an example showing how it works:
.container {
background: silver;
}
.float {
float: left;
}
/* Is this safe? */
.clearfix::before,
.clearfix::after {
content: "";
display: block;
clear: both;
}
<div class="container">
<div class="float">
outer-float
</div>
<div class="clearfix">
<div class="float">
inner-float
</div>
content
</div>
</div>
Using clearance in a ::before
pseudo-element is a bit weird because, while the contents of the element will be placed below the float due to clearance, the float will still overlap the element.
See what happens when you add a background:
.container {
background: silver;
}
.float {
float: left;
}
.clearfix {
background: green;
}
.clearfix::before,
.clearfix::after {
content: "";
display: block;
clear: both;
}
<div class="container">
<div class="float">
outer-float
</div>
<div class="clearfix">
<div class="float">
inner-float
</div>
content
</div>
</div>
Usually what one would want is either clearance on the element itself, or no clearance.
.container {
background: silver;
}
.float {
float: left;
}
.clearfix {
background: green;
clear: both;
}
.clearfix::after {
content: "";
display: block;
clear: both;
}
<div class="container">
<div class="float">
outer-float
</div>
<div class="clearfix">
<div class="float">
inner-float
</div>
content
</div>
</div>
Anyways, note adding clearance to a ::before
pseudo-element is not a clearfix. Clearfixes are hackish techniques used to force a block to grow vertically in order to encompass all its floated contents. That is, clearfixes are a way to emulate block formatting context roots. That's why the clearance should be used after the contents, in the ::after
pseudo-element.