【问题标题】:CSS min-height adds to child element's bottom marginCSS min-height 添加到子元素的下边距
【发布时间】:2017-03-25 10:08:12
【问题描述】:

我遇到了一个非常奇怪的 CSS 问题。我的一些页面在元素之间显示了一个无法解释的“空格”。检查代码显示这个空间不属于任何元素。

我已经缩小了范围,我想我知道为什么会出现这个问题。但我想知道,在幕后,为什么会这样。

我认为,问题在于#outer 选择器中的min-height: 50px#outer 下方添加了#inner 的下边距,这导致了上面提到的无法解释的空间。如果它被替换为height: 50px,空格就会消失。

这发生在 Chrome 而不是 FireFox 上。

我的理论是,Chrome 的 CSS 首先对元素进行布局,然后检查是否满足最小高度要求。如果不是,那么它会扩展 div 的高度,同时推动“无法解释的空间”。它必须复制或继承子元素的下边距。我认为这只会发生在底部边缘。

我已经尝试了这个理论的两个测试,添加padding: 1px; 和添加overflow: hidden; 它们都导致 div 的高度包含它的孩子,从而摆脱了这个问题。虽然,我认为在overflow: hidden 的情况下,它更能切断溢出的内容。

但我不是 CSS 专家,所有这些只是我的猜测,这就是我想提出这个问题的原因:)

这是代码

#outer {
  background-color: blue;
  min-height: 100px;
}
#inner {
  background-color: red;
  height: 50px;
  margin-bottom: 50px;
}
#bottom {
  background-color: green;
  height: 50px;
}
<div id="outer">
  <div id="inner">
  </div>
</div>
<div id="bottom">
</div>

【问题讨论】:

    标签: html css google-chrome firefox margin


    【解决方案1】:

    这是由于 margin collapsing - 特别是 innermargin-bottom 折叠 成为 outer 元素的 margin-bottom

    解决方案

    outer 元素一个 border 以防止边距折叠 - 请参阅下面的演示:

    #outer {
      background-color: blue;
      min-height: 100px;
      border: 1px solid blue;
    }
    #inner {
      background-color: red;
      height: 50px;
      margin-bottom: 50px;
    }
    #bottom {
      background-color: green;
      height: 50px;
    }
    <div id="outer">
      <div id="inner">
      </div>
    </div>
    <div id="bottom">
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2013-06-03
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多