What's the use of :before when clearfix an element?

Here’s how I’ve configured the clearfix HTML element in CSS:

.clearfix:after {
  content: " ";
  display: table;

.clearfix:after {
  clear: both;

I know that :after element is to clear the float but what’s the use case of :before element? Is this for browser compatibility?


AFAIK, the before element is added to avoid collapsing margins, it is not needed to clear floats. That’s why the first ruleblock doesn’t apply the clear property.

The clearfix version you have has a good explanation here:

1 Like

Bear in mind there are few reasons to use clearfix these days as floats are not required for layout like they used to be.

The clearfix technique also wastes the before and after elements which are useful for adding extra decoration to a page without adding extra code.

I rarely used clearfix in the olden days anyway and preferred using block formatting contexts to control any floats (such as overflow:hidden or display:table).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.