Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overflow hidden stop floating elements escaping their container?

Tags:

html

css

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/

like image 455
Chris Avatar asked Feb 08 '12 12:02

Chris


People also ask

Why does overflow hidden not work?

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.

How do you stop a floating element?

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.

How could you stop content wrapping around a floated element?

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.

What keeps the element float on left side of the container?

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).


1 Answers

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

like image 61
Yoshi Avatar answered Oct 09 '22 22:10

Yoshi