The difference is, when using a <br>
(or any other element to make the clearfix), you are inserting an element into the DOM. By using the pseudo-selector ::after
, you insert a pseudo-element into the DOM.
See some examples:
.container {
padding: 10px;
border: solid 2px #000;
}
.box {
width: 33.333%;
height: 50px;
float: right;
}
.clearfix {
clear: both;
}
<div class="container">
<div class="box" style="background: red;">1</div>
<div class="box" style="background: green;">2</div>
<div class="box" style="background: blue;">3</div>
<br class="clearfix" />
</div>
Note in the example above that we use the <br>
to do the clearfix. However, you don’t even need to tweak the HTML to fix it. You can use a pseudo-element (created with the ::after
):
.container {
padding: 10px;
border: solid 2px #000;
}
.box {
width: 33.333%;
height: 50px;
float: right;
}
.container::after {
content: ' '; /* Cria o pseudo-elemento */
display: block;
clear: both;
}
<div class="container">
<div class="box" style="background: red;">1</div>
<div class="box" style="background: green;">2</div>
<div class="box" style="background: blue;">3</div>
</div>
As you saw, the effect is the same.
To learn more, I suggest reading the excellent article "All about Floats". However, it is important to note that if the browsers of your target audience support, you can use the Flexbox, which is a more modern alternative to the so-called floated layouts.
I get it. Thank you!
– Sophia Yuno
You’re welcome, @Sophiayuno. :-) Check out [tour] for the best way to say thank you.
– Luiz Felipe