Doubt between performing clearfix using an element in the DOM or a pseudo-element

Asked

Viewed 23 times

0

I have to wear one float: left in my logo and float: right on my menu, however background-color disappears and need to correct with clear: both.

My question is, what’s the difference between using one <br> after the floating items with clear: both and use the pseudo-selector ::after, making:

::after {
  content: '';
  display: table;
  clear: both;
}

'Cause I’ve seen people use it like that to clean up that little float.

1 answer

0

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!

  • You’re welcome, @Sophiayuno. :-) Check out [tour] for the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.