为什么兄弟元素之间 display:inline-block 能防止 margin塌陷 ?

问一个关于BFC清除兄弟间margin塌陷的问题。希望有人从原理上解答解答。
如图,有两个块级元素发生垂直方向上的margin塌陷

常见的做法有两种,第一种,将下方元素用另一个BFC包裹起来,这种我能理解,因为BFC之间互不影响嘛。

第二种:为下方元素设置浮动或绝对定位或display:inline-block
浮动或绝对定位我也能理解,脱离普通文档流了嘛。
display:inline-block我不是很懂,是因为生成了IFC,BFC和IFC之间不发生重叠?
注意:如果此时只是给<ul>设置overflow:hidden,display:flex,display:table-cell等使其生成BFC都不会发生作用。

代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .first {
        margin: 100px;
        background: lightgreen;
        border: 1px solid;
        width: 100px;
        height: 100px;
      }
      ul {
        /* display: inline-block; */
        /* position: fixed; */
        /* float: left; */
        margin: 100px;
        background: lightblue;
        border: 1px solid;
        width: 200px;
      }
      li {
        margin: 10px 20px;
      }
    </style>
  </head>

  <body>
    <div class="first"></div>
    <!-- <div class="second"> -->
    <ul>
      <li>item1</li>
      <li>item2</li>
      <li>item3</li>
    </ul>
    <!-- </div> -->
  </body>
</html>

希望有人能解答一下关于下方元素设置dispaly:inline-block可以解决margin塌陷的原理。

阅读 900
2 个回答
✓ 已被采纳

因为标准就是这么写的:

8.3.1 Collapsing margins

  • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  • 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.
  • Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).
  • Margins of inline-block boxes do not collapse (not even with their in-flow children).
  • ...

方法二和方法一避免margin合并的原理是一样的,都是生成了一个新的BFC啊。
image.png
image.png

—————————————————————
box model collapsing margin

Two margins are adjoining if and only if:
both belong to in-flow block-level boxes that participate in the same block formatting context

不知道我理解的对不对,我说一下我的理解。我一直认为只要生成了新的BFC就会避免边距折叠,但是今天看了官方说明之后,觉得这并不对吧,只是恰好是这样的。就以这个问题的情形来说(这两个元素的父元素相同)。

  • 当我们使用float或absolution position的时候,它会out-flow,那么belong to in-flow block-level boxes是不是就不成立了?(我不确定belong to in-flow block-level boxes的判断依据是什么,我猜应该是不成立了。)
  • 当我们使用display: inline-block的时候,这个元素参与的是IFC,会创建一个line boxes来包含它,是不是belong to in-flow block level boxes也不成立了?
  • 在一个block boxes上设置除overflow,值除了visible时,上面的条件依然是成立的。所以这里并不合并。如果它们这两个元素的父元素不同,但是也是挨着的话,我们设置其中的一个父元素为display:inline-box,可能会使后面的in the same block formatting context不成立。

并不是生成BFC就可以避免边距的折叠,主要看外边距折叠的充要条件使如何定义的。而生成一个BFC恰好使得在大多数情况下,外边距折叠的条件不成立。

参考资料:

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题