It is so simple to clear floating HTML elements with overflow:auto but this doesn’t seem to be common knowledge. The most common way to clear floats is with a float clearing div; a hackish method involving writing content using the :after pseudo property; or unbelievably using <br clear="all"> as I saw posted on another site yesterday. This post looks at the simplicity of overflow:auto.
Example
Here is what we are trying to achieve: a container with some floating divs and a border that extends around all child elements. Any subsequent content should appear after the container.
The traditional float clearing method
Here is the HTML with inline CSS to show the above using the traditional float clearing method, which involves putting a clear:both style div inside the end of the container. The class name is typically something like "clear":
<div style="border:1px solid #000; width: 510px;"> <div style="width:250px; float: left; background-color: #ccc; margin-right: 10px;">...</div> <div style="width:250px; float: left; background-color: #ccc;">...</div> <div style="clear:both"></div> </div>
Using overflow:auto in the container
And here’s the nicer way of making the container extend to the height of the largest child using overflow:auto. This negates the need for additional markup in the form of the clearing div and means all the work can be offloaded into an external stylesheet. Note again I have used inline CSS for this example to make it clear what each div is doing.
<div style="overflow:auto; border:1px solid #000; width: 510px;"> <div style="width:250px; float: left; background-color: #ccc; margin-right: 10px;">...</div> <div style="width:250px; float: left; background-color: #ccc;">...</div> </div>
A note on IE6
In order to get this to work in IE6, hasLayout needs to be triggered. This is done when the width or height of an element is set but if you do not want to set the width or height, you can instead trigger hasLayout with the proprietary Microsoft zoom CSS property like so:
.myDivWithFloatingChildrenLayers { overflow: auto; zoom: 1; }
or inline:
<div style="overflow:auto; zoom:1">...</div>
Conclusion
Using overflow:auto is a much tidier way of ensuring the container is the same height as its maximum child element because it no longer requires littering the HTML source with clearing divs. This method works in all browsers including IE6.