加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

html – 块格式化上下文中“溢出”值除“可见”以外的影响

发布时间:2020-12-14 16:43:20 所属栏目:资源 来源:网络整理
导读:这个问题类似于 this one(有一个很好的答案),虽然我的不涉及浮动问题. 我最近在尝试将边距应用于块级元素的唯一子节点时遇到了一些麻烦: #parent { background: rgba(255,0.1);}#child { margin: 30px 0; padding: 20px; background: rgba(0,255,0.1);} div
这个问题类似于 this one(有一个很好的答案),虽然我的不涉及浮动问题.

我最近在尝试将边距应用于块级元素的唯一子节点时遇到了一些麻烦:

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

这解释了为什么在您尝试阻止边距崩溃之前,父级的背景不会延伸.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读