A new solution just popped up that enables clearing of floats without the markup hacks of old. Great! Except there’s a caveat: scrollbars.
First reported on this SitePoint blog entry, later followed up with a description and some test cases by Anne van Kesteren, a new method of clearing floats involves using
overflow: auto; to expand the parent and contain all children, thus forcing it to contain even floated elements within.
overflow: auto is working for us in this case when it comes to vertical overflow, unfortunately it also applies to horizontal overflow as well. Therefore, all child elements must be smaller than or equal to the width of the parent, otherwise ugliness occurs.
Some examples are in order. First, here’s our basic setup:
- Example 1 — The problem.
We have two pargraphs side by side, contained within a parent div. We want the border of the div to surround both paragraphs; because they’re floated, though, the border of the parent doesn’t surround either and bunches up at the top as a solid grey bar.
There are now two methods to force the parent to expand and include the children; traditionally, you could have applied a
float: left; to the parent and found some way to work around the resulting float. Or now with the new method, you don’t have to worry about any re-positioning of the parent after all, because the overflow property doesn’t affect it the way a float would:
(Note that due to positioning in these examples, the floated parent layout issues aren’t apparent; it would take extra complexity to demonstrate that, but if you’re at all familiar with floats it shouldn’t be too much of a stretch to see how the floated parent would be problematic.)
What happens, though, if the child element is simply too large for the parent? This may be triggered in environments where dynamic content might see the addition of an image with particularly large dimensions, or by something silly like the italicized text problem in Win/IE.
Ah. And so we reach the crux of the matter. Neither solution is perfect, they both have the same problem with horizontal overflow. Each handles it in a different way. The
overflow method doesn’t require extra positioning aerobics to adapt to the position of a floated parent, but its method of handling overflow may be more problematic than the float method.
It’s always great to have another tool in the arsenal, but remember that the Achilles’ heel of this one is the horizontal scrollbars you may experience in your layout.