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 trialFabrício Montenegro
18,723 PointsExplain 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
Jason Anello
Courses Plus Student 94,610 PointsHi 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
18,723 PointsThanks a lot, bro!
Jason Anello
Courses Plus Student 94,610 PointsYou're welcome!
Fabrício Montenegro
18,723 PointsFabrício Montenegro
18,723 PointsWow, 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?
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsAlso, you might see older markup like this:
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.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsThis link should help with explanations of the properties used like
table
A new micro clearfix hack