Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Layout Techniques Float Layout The Float Clearfix

Fabrício Montenegro
Fabrício Montenegro
18,723 Points

Explain clearfix

In this lesson we are told that we can use some css to fix the collapsing problem when an element .group has floating children. This is the code:

.group::after {
   content: " ";
   display: table;
   clear: both;
}

Now, I don't really get it. What does it do? I know ::after will insert a pseudo-element after the .group element, but how an element outside the parent will clear its children? And why does it have a display: table;? I know it works and I could use it from now on but I really wanna understand how it works.

2 Answers

Hi Fabricio,

::after doesn't insert content after the .group element but rather at the very end of the element before the closing tag. This mdn page, ::after (:after), refers to it as matching a virtual last child.

So the idea is that you're inserting invisible content as the last child of a parent. Since this generated content clears the floats it will drop below all previously floated elements. Since this generated content is not floated itself, the parent element must expand all the way down to contain it. Automatically containing all the floated children that came before.

Fabrício Montenegro
Fabrício Montenegro
18,723 Points

Wow, my life was a lie! Thanks for clearing out what :after actually does. Your explanation was pretty good. :D

But how about the table display?

Also, you might see older markup like this:

<div class="container">
    <p>Some paragraph that has been floated left</p>
    <div style="clear: both"></div>
</div>

This empty div at the end is acting as the clearing element which causes the "container" div to contain the floated paragraph. This works but your markup is now cluttered with an empty div which is only there for presentational reasons.

The clearfix technique is a replacement for this. It does the same thing and allows us to keep content and presentation separate.

This link should help with explanations of the properties used like table

A new micro clearfix hack

You're welcome!