A common problem that I have with web pages is floating divs creeping outside of their containers.
#wrapper{
border:1px solid red;
}
#wrapper div{
float:left;
font-size: 3em;
}
...
<div id="wrapper">
<div>Hello World</div>
</div>
Live example: http://jsfiddle.net/ugUVa/1/
There are a lot of dirty ways to fix this (inserting a div with clear:both)
A much neater solution I have seen is setting the wrapper divs overflow style to hidden:
Example: http://jsfiddle.net/ugUVa/2/
This works well across browsers, nice and cleanly with no additional markup. I am happy, but I have no idea WHY it works!
All the documentation I have looked at indicates overflow:hidden is for hiding content, not resizing a parent to fit its children...
Can anybody offer a explanation for this behavior?
Thanks
It's correct that the
overflow
style is intended to control what happens to overflowing content.The effect on the floating elements is a side effect of the
overflow
style creating a block formatting context for the element.When you don't specify a size for the containing element, the block formatting context gets its size from the elements that it contains, so that is the size that the containing element gets.
It creates a block formatting context.
see also: http://www.w3.org/TR/CSS2/visuren.html#block-formatting