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

作者站长头像
站长
· 阅读数 12

问一个关于BFC清除兄弟间margin塌陷的问题。希望有人从原理上解答解答。如图,有两个块级元素发生垂直方向上的margin塌陷为什么兄弟元素之间 display:inline-block 能防止 margin塌陷 ?

常见的做法有两种,第一种,将下方元素用另一个BFC包裹起来,这种我能理解,因为BFC之间互不影响嘛。为什么兄弟元素之间 display:inline-block 能防止 margin塌陷 ?

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

代码如下:

<!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塌陷的原理。

回复
1个回答
avatar
test
2024-06-20

因为标准就是这么写的:

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).
  • ...
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容