A common problem that I have with web pages is floating div
tags creeping outside of their containers, like shown in the snippet.
#wrapper {
border: 1px solid red;
}
#wrapper div {
float: left;
font-size: 3em;
}
<div id="wrapper">
<div>Hello World</div>
</div>
There are a lot of dirty ways to fix this (i.e., inserting a div
with clear:both
)
However, a much neater solution I have seen is setting the wrapper div
with overflow
set to hidden
:
#wrapper {
border: 1px solid red;
overflow: hidden;
}
#wrapper div {
float: left;
font-size: 3em;
}
<div id="wrapper">
<div>Hello World</div>
</div>
This works well across browsers, nice and cleanly with no additional markup. I am happy, but I have no idea WHY it works this way?
All the documentation, I had 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
Original snippets: Live example 1: http://jsfiddle.net/ugUVa/1/ Live example 2: http://jsfiddle.net/ugUVa/2/
clear:both;
div, but with no additional markup. See my example: jsfiddle.net/TheNix/fSBhT and an article on it: nicolasgallagher.com/micro-clearfix-hack:after
to achieve this (andzoom: 1
to reproduce the effect in IE 6 and 7, which don’t support:after
) — see perishablepress.com/press/2009/12/06/new-clearfix-hack