我最近在尝试将边距应用于块级元素的唯一子节点时遇到了一些麻烦:
#parent { background: rgba(255,0.1); } #child { margin: 30px 0; padding: 20px; background: rgba(0,255,0.1); }
<div id="parent"> <div id="child">Foo</div> </div>
虽然应用了保证金,但父母的背景却不是.除非在#child之前和之后添加兄弟姐妹,否则这仍然是正确的,或者(在我看来更有趣),设置除了可见之外的任何值的溢出.这是相同的示例,但具有溢出值:
#parent { background: rgba(255,0.1); overflow: auto; } #child { margin: 30px 0; padding: 20px; background: rgba(0,0.1); }
<div id="parent"> <div id="child">Foo</div> </div>
从CSS2.1 Section 9.4.1 – Block Formatting Contexts开始,我发现了以下内容:
Floats,absolutely positioned elements,block containers (such as inline-blocks,table-cells,and table-captions) that are not block Boxes,and block Boxes with ‘overflow’ other than ‘visible’ (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
在这个例子中,我真的很难理解“溢出而不是可见”逻辑背后的基本原理.在这种情况下,边缘似乎没有被削减,因为唯一要改变的是背景.有人可以证明为什么溢出值:可见会产生这种情况吗?
解决方法
虽然浮点数和崩溃边距之间的关系非常简单(它永远不会发生),但是边距不能通过具有这样的溢出值的元素的边界折叠这一事实只不过是这种变化的副作用,因为边距是定义为不通过任何建立块格式化上下文的框折叠,如section 8.3.1中所述.我引用:
- Margins of elements that establish new block formatting contexts (such as floats and elements with ‘overflow’ other than ‘visible’) do not collapse with their in-flow children.
这包括浮点数和具有溢出值的元素.溢出本身实际上对边距没有任何直接影响.
当父级和子级都是参与相同块格式化上下文的块级元素时,默认情况下它们将崩溃,除非有某些方法:
The top margin of an in-flow block element collapses with its first in-flow block-level child’s top margin if the element has no top border,no top padding,and the child has no clearance.
The bottom margin of an in-flow block Box with a ‘height’ of ‘auto’ and a ‘min-height’ of zero collapses with its last in-flow block-level child’s bottom margin if the Box has no bottom padding and no bottom border and the child’s bottom margin does not collapse with a top margin that has clearance.
这解释了为什么在您尝试阻止边距崩溃之前,父级的背景不会延伸.