【问题标题】:Why don't inline-flex containers' margins collapse?为什么 inline-flex 容器的边距不会崩溃?
【发布时间】:2021-04-05 22:17:35
【问题描述】:

我了解项目一个弹性容器中遵守与正常情况不同的边距折叠规则(即,当不在弹性包装器内时)。但是,容器本身的边距应该仍然正常运行,对吧?换句话说,为什么this CodePen中两个容器的margin不一样?

border collapse example

h1, h2 {
  margin: 2rem 0;
}

.inline-flexed,
.flexed {
  margin: 2rem 0;
  align-items: center;
}

.inline-flexed {
  display: inline-flex;
}

.flexed {
  display: flex;
}

.left {
  display: inline-block;
  width: 2rem;
  height: 2rem;
  background-color: blue;
}

.right {
  line-height: 1.5;
  background-color: lightgray;
}
<h1>I have margins!</h1>

<span class="inline-flexed">
    <span class="left"></span>
    <span class="right">My container is inline-flex'ed. For some reason my parent's container's margins don't collapse.</span>
</span>

<h2>I also have margins!</h2>

<span class="flexed">
    <span class="left"></span>
    <span class="right">My container is flex'ed. My parent's container's margins collapse as you'd expect.</span>
</span>

<h2>Is this a browser bug?</h2>

【问题讨论】:

标签: css margin display


【解决方案1】:

inline-flex 生成一个 flex 容器,它是 inline-level 元素。 inline-* 元素的边距不会折叠。


这里有记录。

内联弹性

当放置在流布局中时,该值会导致元素生成 内联级 的 flex 容器框。 w3

两个边距相邻当且仅当:

  • 两者都属于参与相同块格式化上下文的in-flow block-level框。

  • 没有线框,没有间隙,没有填充,也没有边框将它们分开(请注意,某些零高度的线框(请参阅 9.4.2)为此被忽略。)

  • 两者都属于垂直相邻的盒子边缘。 w3

类似问题

Margin collapsing in flexbox

更多信息

https://www.joshwcomeau.com/css/rules-of-margin-collapse/

https://www.smashingmagazine.com/2019/07/margins-in-css/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2017-11-07
    • 2023-03-14
    • 1970-01-01
    • 2011-06-11
    • 2012-04-20
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多