What is clearfix:before and clearfix:after ?

As a front end developer we mostly use .clearfix class, I am using it with two different selectors


.clearfix:before
.clearfix:after {}

Most of the beginners and few of the experts still use .clear class. I have already discussed .clear class in my article CSS Floats and CSS Clear DIV’s so i will not go into its details. Lets focus on clearfix class and its two selectors.

Basically the code i am using and Twitter Bootstrap and other modern frameworks use for .clearfix class is something like


.clearfix:before,
.clearfix:after {
display: table;
content: " ";
}

.clearfix:after {
clear: both;
}

.clearfix is basically not itself implemented on a div, we normally use it as a combination like

div content goes here....

though its not necessary that it cannot be used on a div without combining with other classes but its in most cases used with other classes as it doesn’t have any weight on itself and we prefer not to declare any other functionality with .clearfix so it always stays clean and minimal and it can be used with any class. So what is :after and :before, they are simple selectors. :after is called when the div is closed while :before comes before the div, so it kind of tells the div to clear both sides left and right before its div and after it’s div. So it gets a box shape even if its child elements are floating to left or right. It always clear its predecessor div’s and will not let any div overlap it, will tell the div after it to accommodate itself below the div’s content.

content: ” “; means to have a simple space if there is no content in the div this class is assigned to.

display: table; is basically telling the div to behave like a table. Its another story so i wont go into its details.

I will suggest using this class rather than defining your own class as its simple and it kind of evolved into a standard. So anywhere i see this class its clear to me its reasons for being there.