Clearfix Hack

Clearfix Hack

Essentially, this clearfix hack revolves around the ::after pseudo element. If you have never heard of the ::after pseudo element, the following is one way it can be used:

HTML:

<p>Let’s go</p>

CSS:

p::after {
  content: “ to the movies!”;
}

RESULT:

Let’s go to the movies!


The ::after pseudo element is used to put additional content at the end of the current content within the <p> element.

However, for layouts, one use is to fix shifting elements when using floats. To elaborate, when an element is floated, the content below it shifts up. This is because the floated element is essentially removed from the normal flow of the content. When the clearfix hack is used in the parent element, such as a <div> element, the content below the <div> element sees the presence of a cleared float, and consequently can’t shift up. Check out the HTML and CSS in the CodePen above.

Interestingly, the ::after pseudo "element" is being inserted after the <div> element’s content—NOT after the <div> element. As a result, before the closing </div> tag, the content of nothing (content: "") is set to display: block, and this block "element" of nothing is assigned to clear the float. At which point the content below the <div> element can no longer shift up.

Photo by Anamul Rezwan from Pexels