overflow:hidden on div标签会影响背景颜色 [英] overflow:hidden on div tag affects background color
问题描述
overflow:hidden
的定义说明:
溢出的内容完全隐藏,用户无法访问。
从:
但是, overflow:隐藏
可防止:
建立新的块格式化上下文的元素的边距(例如
以及The definition of
overflow:hidden
states that :
the overflowing content is completely hidden, not accessible to the user.
from: http://quirksmode.org/css/css2/overflow.html
But i am curious about this behavior from my js fiddle: https://jsfiddle.net/gd62qmr3/2/
One thing i noticed is that, it gave color to the margins after setting the overflow to hidden?
<div style="background-color:green;overflow:hidden;"> <p>test</p> </div>
I wanna know why did such behavior occur? the exact block element will have the green background color if there is no overflow but putting overflow will give background color to its margins.
解决方案That's because
overflow: hidden
affects margin collapse.
p
elements have some vertical margin by default. According to the spec, it collapses with the margin of the parentdiv
:In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
Adjoining vertical margins collapse, except [... not relevant]
[... The] top margin of a box and top margin of its first in-flow child [are adjoining]
However,
overflow: hidden
prevents that:Margins of elements that establish new block formatting contexts (such as floats and elements with
overflow
other thanvisible
) do not collapse with their in-flow children.这篇关于overflow:hidden on div标签会影响背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!