
Div Containers with Floats: clearing
July 6, 2008If you have ever tried to format a website using floating objects then you have no doubt run into a problem when a ‘container’ div doesn’t stretch to hold the floats. Instead, it has no height at all, pulling any objects below it up into your floated objects and messing up borders.
The popular (though messy) way to fix this is to add a
<div style="clear:both;"></div>to the bottom of the containers code. This gives the container some non-floated content (below the floated objects) and thus expands the size to the correct dimensions.
The main problem with this (from my point of view) is that it looks awfully messy, especially if you are creating a template. Having a bunch of empty divs lying around just seems like poor form.
Anyway, today I found a better solution – a much more thorough explanation of the issue (with pictures), the solution and why it works can be found at www.quirksmode.org.
Basically though, including:
overflow:hidden;in the css for the container will force the container to expand to the correct size. You can also use ‘overflow:scroll’ but this will give you scroll bars in the container (which looks bad most of the time). (Using ‘hidden’ seems to be the best option because ‘auto’ can also cause scroll bars to appear in some browsers)
or
overflow:auto;
One line of CSS seems preferable to extraneous divs sitting around in the HTML.