Best clearfix ever
I rarely name my articles best or ultimate as I think those terms are abused quite a lot on the internet. But in this case I am going to make a special exception as I believe the clearfix that I want to discuss, is a little bit better than the original.
Most web developers probably know about clear float problems and our two basic solutions for them which I'll discuss briefly.
The first solution is the clear div fix which is an extra div we slot in our HTML.
/* Global CSS file */
.clear-float { clear:both; display:block; height:1px; margin:0 0 -1px 0; overflow:hidden; width:100%; }
The second solution is to add content after a div forcing it to clear, this is known as the clearfix solution.
/* Global CSS file */
.clearfix:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
/* ie CSS file */
.clearfix { zoom:1; }
Both techniques have problems. The clear-float solution is bad as you are adding extra markup to our crisp clean HTML. The clearfix is a problem as you have to add it to all your divs that require the fix. This is time consuming and adds CSS class names when not necessary.
The best solution that I could think of is to create an automatic clearfix. I add this to all my block level elements.
/* our Global CSS file */
article:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
aside:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
div:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
form:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
header:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
nav:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
section:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
ul:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
/* our ie CSS file */
article { zoom:1; }
aside { zoom:1; }
div { zoom:1; }
form { zoom:1; }
header { zoom:1; }
nav { zoom:1; }
section { zoom:1; }
ul { zoom:1; }
Our clearfix solution now works automatically. What you do need to remember is that certain elements may not collapse correctly so use padding to align elements vertically. Once you do that, you never have to worry about clear float problems again.