What is CSS clearfix and how to use it?

Published 03 Feb by SuperNOVA

What is CSS clearfix and how to use it?Anyone who has ever used the grid layout would know that using floats can sometimes be a pain in the a$$. So, lets explore the problems we face a bit.

The Problem with floats

The very first problem with using floats is that if all the child elements of a container are given a float value, then the parent element gets a height of ZERO.
This means that the border of the parent element will not be applied properly, you will have a very hard time using the heights in javascript animations or calculations.
Check out the following code and what it will look like without any clearfix.
This is the child element 1
This is the child element 2
Notice the deformed border on the above element.

I hope you see the problem :D, and if you are wondering what style I applied to the * then you should read this post.

How to fix the problem with floats

  • Insert a clear div: This is an old method but works very well. What you do is put a div after the floated elements like <div class=”clear”></div> and then give it styling as such. The problem with this method is that you will have to add an extra element in your layout which is not preferred sometimes.
  • Add overflow and width to the parent element: Consider this styling for the parent element: Adding the overflow property forces the element to clear its child floated elements thus, providing a solution to our problem. Some browsers need a width for this to work. For example, in explorer providing a width triggers the hasLayout.
    Now, what troubled me when I found this solution was that the overflow property has a default value of auto, so why doesn’t this trick work by default. I am still looking for a valid answer but apparently CSS works this way :P
    P.S. The credits for this go to quirksmode who apparently saw it from somewhere else.
  • Use the :after pseudo class: This is my favourite, partly because I didn’t read it somewhere else, discovered it on my own( really not boasting :P ).But anyway, here it is: The advantage with this method is that you don’t need any extra HTML unlike the first method, while an obvious disadvantage is the use of :after might reduce your browser compatibility due to browser support. Check your requirements here.

After applying any of the above fixes, you should see the following result:

This is the child element 1
This is the child element 2
Notice the border on the above element is now fine.

Well, sometimes the issues with floats are not visible to use maybe due to the architecture we used, and even when we are facing the mentioned problem, one technique might favour the situation more than other. So, you should be aware of what all ways are present to tackle your problem.

There might be easier methods to achieve the required effect and if you do know some other method or found some problem with the ones mentioned above, please share them with us!