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

winkkkkk9421

问一个关于BFC清除兄弟间margin塌陷的问题。希望有人从原理上解答解答。 如图,有两个块级元素发生垂直方向上的**margin塌陷** 。 ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241007/193f3c71ab6cbe18a500894db6b8a556.png) 常见的做法有两种,第一种,将下方元素用另一个BFC包裹起来,这种我能理解,因为BFC之间互不影响嘛。 ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241007/cff4f438e12b0b38c355283a3413b3ed.png) 第二种:为下方元素设置浮动或绝对定位或`display:inline-block`。 浮动或绝对定位我也能理解,脱离普通文档流了嘛。 `display:inline-block`我不是很懂,是因为生成了IFC,BFC和IFC之间不发生重叠? **注意:** 如果此时只是给``设置`overflow:hidden`,`display:flex`,`display:table-cell`等使其生成BFC都不会发生作用。 ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241007/174bcae1c9c9114d37675079e266cb05.png) 代码如下: Document * { 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; } --> item1 item2 item3 --> 希望有人能解答一下关于下方元素设置`dispaly:inline-block`可以解决`margin塌陷`的原理。

阅读量:127

点赞量:0

问AI
因为标准就是这么写的: «"8.3.1 Collapsing margins" (https://link.segmentfault.com/?enc=LoDRLhkXjKh3qL5uh%2BzayA%3D%3D.nLjxdIxgXr0oRiCrcm%2B1DHjsOHwQZNzyHf5cdsncMb%2FO4vF2MfF5UV0FH7PS3CofGuiYCt9FJhDJYtS3xjD2zA%3D%3D)* 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). * ...»