[css] 外边距合并(折叠) / 子元素margin-top影响父级margin-top的处理

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.

在css中多个毗邻的盒子的外边距会合并组成一个单独的外边距,这种合并称之为collapse

对于毗邻的定义是:
Two margins are adjoining if and only if:

  1. both belong to in-flow block-level boxes that participate in the same block formatting context
  2. no line boxes, no clearance, no padding and no border separate them (Note that certain zero-height line boxes (see 9.4.2) are ignored for this purpose.)
  3. both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
    • top margin of a box and top margin of its first in-flow child
    • bottom margin of box and top margin of its next in-flow following sibling
    • bottom margin of a last in-flow child and bottom margin of its parent if the parent has ‘auto’ computed height
    • top and bottom margins of a box that does not establish a new block formatting context and that has zero computed ‘min-height’, zero or ‘auto’ computed ‘height’, and no in-flow children

需要注意的是:

  1. 水平方向的外边距不会发生合并。
  2. 竖直方向除了下面的情况会发生合并。
    • 根元素外边距不会发生合并。
    • 具有上下外边距的元素会与兄弟元素发生合并,但是不会与父元素的下边距合并。

根据以上关于毗邻的定义和外边距发生合并的条件,可以轻松解决子元素margin-top影响父级margin-top的问题,只要使其不满足毗邻条件即可,比如填充内容,加边框,加内边距等。

那么为什么overflow:hidden, 可以解决子元素margin-top影响父级margin-top的问题?

  1. 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.
  2. Margins of the root element’s box do not collapse.
    原因在于overflow不包含visible的其他属性(如overflow:hidden)会为自己的内容创建一个新的“块格式上下文”(BFC),拥有overflow:hidden这个属性的元素可以理解为新上下文的根元素,由外边距合并发生条件中,根元素不会发生合并。所以overflow:hidden也可以处理标题中提到的问题。

参考信息:Collapsing marginsBlock formatting contexts

collapsing-margin.png

https://www.doctype.com.cn/archives/261/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值