Self Clearing Floats, Is It Really So Hard?
23, February, 2010No matter how many times I say it and no matter how many times I show people, I still get this <div style=“clear:both;”>. This drives me nuts! If it is not an empty div with a style attribute then it is clearfix classes on the floated items and not on the parent as they should be.
Let me say it loud and let me say it clear empty divs are meaningless and clearfix classes go on the parent element! Okay rant over, now if you are not sure how to self clear floats then here are a few easy ways to do it.
Clearfix
You can add clearfix to the parent element that has floated children, this will force the parent element to wrap around the children and contain them. Not sure what the clearfix code looks like, well this should explain it all.
Overflow Hidden
This can be tricky as you have to make sure that you are happy to hide the overflow, otherwise funny things can happen. For example adding overflow hidden to a un-ordered list that is really a drop down menu is not wise. Overflow hidden will self clear a float but IE6(if you still care) needs hasLayout to be triggered. Needless to say hasLayout is long and boring so I am not going to go there but you can get around this by applying the well known triggers for IE6 like zoom:1 or height:1%. Of course as any respected person does, this should be added to your IE6 conditional commented stylesheet.
Floating
Floating the parent will also make it contain its children, again caution should be exercised as you then can run into the problem of content being floated around your element when all you needed was to have it clear.
There you go some quick ranty tips, not very in depth but then it is more of a rant than instructional.