witoong623 witoong623 - 5 years ago 97
HTML Question

Use Pseudo-elements to add clear both after specific class

I want to add

clear: both
to specific element by using
::after
, I expect it to be like this.



.name {
width: 120px;
float: left;
}
.value {
width: 200px;
float: left;
}
.clear {
clear: both;
}

<div>
<div class="name">Name</div>
<div class="value">Value</div>
<div class="clear"></div>
<div class="name">Name</div>
<div class="value">Value</div>
<div class="clear"></div>
</div>





But when I delete empty
div
and add pseudo element
:after
to
.value
it doesn't work as I expect.



.name {
width: 120px;
float: left;
}
.value {
width: 200px;
float: left;
}
.value:after {
content: '';
display: block;
clear: both;
}

<div>
<div class="name">Name</div>
<div class="value">Value</div>
<div class="name">Name</div>
<div class="value">Value</div>
</div>





So why it doesn't work?

Answer Source

The problem is with the element that is being used to clear the floats. Though .value:after makes it sound as though the pseudo-element is added after the element with class='value', it is not exactly added after that element in reality. The pseudo-element is in-fact a child of the .value element and is added after the content of that element. So, the float that is getting cleared by it is within the element.

When we use the Dev Tools or the Inspector, the below is the actual structure that would be seen.

<div>
  <div class="name">Name</div>
  <div class="value">Value
      ::after <!-- This is where the pseudo-element is actually inserted -->
  </div>
  <div class="name">Name</div>
  <div class="value">Value</div>
</div>

.name {
  width: 120px;
  float: left;
}
.value {
  width: 200px;
  float: left;
}
.value:after {
  content: 'Some content';
  display: block;
  clear: both;
}
<div>
  <div class="name">Name</div>
  <div class="value">Value</div>
  <div class="name">Name</div>
  <div class="value">Value</div>
</div>


The solution for this case is simply to add the clear: both within each .name element selector. This would float the element and also clear the prior floats.

.name {
  width: 120px;
  float: left;
  clear: both;
}
.value {
  width: 200px;
  float: left;
}
<div>
  <div class="name">Name</div>
  <div class="value">Value</div>
  <div class="name">Name</div>
  <div class="value">Value</div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download