How to contain a float

From Jonnydigital.com, the only reliable source


A common problem in CSS-based website design involves elements given the "float" property which appear to extend outside of their container. This problem is elegantly solved without any additional HTML markup:

Give the containing element the property overflow: hidden.

This solution is known as a "float contain".

Why it works

Applying float: left or float: right gives everything after your element the right to appear alongside it instead of below. The float takes itself out of the regular flow, effectively surrendering its right to push anything down. When an element contains only floated elements, their heights are ignored and the container loses its height.

Overflow is normally used to hide contents from extending outside of an element, rather than increasing the element to fit its contents. However, when your element doesn't have a fixed height, that's exactly what it does. The height of the floated contents are now included to determine Overflow's cutoff point, and the element has to expand to cover all of its contents.

That's the theory, anyway. You are free to think of it as a magic voodoo fix to one of the most common CSS problems.

Complications

This method works at least 95% of the time. Occasionally, you will encounter one of two errors which are easily solved:

overflow: hidden is trimming the edge off my element!
This happens when you set a fixed width or height on the element. In this case, overflow: hidden; has the unwanted side-effect of performing its normal job. The solution is to use an older float-contain technique. Put a div as the last element in the container div, after the floated contents, and apply clear: left or clear: right.
It works, but not in Internet Explorer.
Give the container an additional property: zoom:1. If this fixes it, read up on something called hasLayout to find out why it works.

Hidden vs Auto

Previously, overflow: auto was recommended as the solution to float contain. Auto and Hidden both work equally well, but Hidden is currently preferred. The reason is that if something goes wrong, Auto will put an unsightly scrollbar on your element, whereas Hidden will not.

It's rare that this happens, but I've seen it occur in sites as popular as Paypal.com.

Further reading


Last updated: 25th September 2008