There has been many ways over the years to give the height back to the background of a container around floating elements.
First Version
This was the first method I spotted years back. This method which left a 1px gap at the end and other unwanted problems.
1 2 3 4 5 | <!-- .clear { clear: both; } --> |
1 2 3 4 5 |
Second version
The next one replaced the extra HTML for a CSS class which added the content in after the divs through the CSS. The CSS hacks essentially fix all the problems with the above version and some.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!-- .clearfix:after { content: "."; /* Adds content to show the containing box where to end it's rendering */ display: block; height: 0; /* Prevents the content from adding any more height to it's parent */ clear: both; /* keeps this content under the floating elements */ visibility: hidden; } .clearfix { display: inline-block; } /* Hides from IE-mac \*/ * html .clearfix { height: 1%; } .clearfix { display: block; } /* End hide from IE-mac */ --> |
1 2 3 4 |
Latest
This removes most of the hacks. Makes a cleaner CSS and markup and seems to suit me well.
1 2 3 4 5 6 7 8 9 10 11 | <!-- #container { overflow: auto; /* if this element has padding user overflow: hidden; */ } /* IE6 stylesheet needs hasLayout turned on */ #container { zoom: 1; } --> |
1 2 3 4 |
Further information
Info on hasLayout
http://www.satzansatz.de/cssd/onhavinglayout.html
4 years ago sitepoint posted this:
http://www.sitepoint.com/blogs/2005/02/26/simple-clearing-of-floats/
If you find one nicer, please let me know in the comments. Or if you have a case where this doesn’t work. Send me some sample code.
