I ran into the pervavise issue of having to clear a DIV that contains only floated DIV elements in it recently. The problem is that the outer container does not stretch to accomodate the height of it’s child containers. So, if you have a background or a border on the containing element, it does not fully cover the child elements.
It’s an old issue, but I keep forgetting where to find the information on how to fix it. So, this is a note to self for future reference.
I found the following resources to be the most useful in terms of the pros and cons of each technique. Please see them for more detailed instruction. I’ve summarized the basics below.
- See CSS Clearing Floats on Stackoverflow
- See Clearing Floats on Quirksmode
- See Which Method of ‘clearfix’ is Best? on Stackoverflow
- See How to Clear Floats Without Structural Markup
Add an Empty DIV and clear:both Styling
The easiest, and oldest, fix is to add an empty DIV with a style of clear:both to the end of the outer container. This works, but it’s not semantic and makes a mess of the page’s markup.
1 2 3 4 | |
1 2 3 4 5 | |
Use the clearfix Hack
Beyond adding additional markup to the page, you can use the infamous ‘clearfix’ hack, which cheats by adding additional content after the containing element. While this prevents you from having to muddy the markup on the page, it feels a bid hackish to me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Use the overflow:hidden Technique
The method I’ve tended to use and that has the least problems in my experience is the overflow method, with some additional css to trigger hasLayout in IE.
This method works great as long as there is no fixed height on the outer container. See Quirksmode for ways to resolve issues related to this technique.
I’ve seen some references indicate that you can use overflow:auto to achieve the same results, but you risk having scrollbars show. So far, the overflow:hidden method has been the cleanest and most efficient technique for me.
1 2 3 4 5 6 7 8 9 10 11 12 | |