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/
It is because you are using position absolute. You cannot use position absolute with overflow hidden, because position absolute moves the targeted element out of context with the document structure.
Clearing Floats To clear a float, add the clear property to the element that needs to clear the float. This is usually the element after the floated element. The clear property can take the values of left , right , and both . Usually you'll want to use both.
CSS Clear property is used to stop next element to wrap around the adjacent floating elements. Clear can have clear left, clear right or clear both values.
The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow (in contrast to absolute positioning).
It creates a block formatting context.
Block formatting contexts are important for the positioning (see float) and clearing (see clear) of floats. The rules for positioning and clearing of floats apply only to things within the same block formatting context. Floats do not affect the layout of things in other block formatting contexts, and clear only clears past floats in the same block formatting context.
see also: http://www.w3.org/TR/CSS2/visuren.html#block-formatting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With