Why does overflow hidden stop floating elements es

2020-01-24 12:26发布

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

标签: html css
2条回答
一纸荒年 Trace。
2楼-- · 2020-01-24 12:30

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.

查看更多
ら.Afraid
3楼-- · 2020-01-24 12:48

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

查看更多
登录 后发表回答