【问题标题】:Why does adding a border change the behavior of the background color?为什么添加边框会改变背景颜色的行为?
【发布时间】:2012-11-09 02:28:23
【问题描述】:

在下面的示例中,为什么移除 #enclosure div 上的边框会使背景浅蓝色不再填充整个 div 背景?

#enclosing
{
  background: lightblue;
  margin: 0;
  border: 1px solid blue;
}

#outer
{
  margin: 40px;
}

#inner
{
  margin: 20px;
  border: 1px solid black;
}​

<div id="enclosing">
    <div id="outer">
      <div id="inner">This is nested div</div>
    </div>
</div>

JSFiddle 上的示例

【问题讨论】:

    标签: html css


    【解决方案1】:

    outer div 有边距,需要“推动”一些东西。

    当封闭的 div 没有边框(或填充)时,outer div 的边距没有任何东西可以推动。

    在 div 的顶部/底部添加边框或填充为其提供了必要的包含,以便 outer div 计算关闭。

    我相信这就是Box Model 中所谓的collapsing margins

    【讨论】:

    • 可靠的答案。如果您想要即使没有边框也有粗蓝色边框,请在#outer 上使用填充而不是边距,您应该会看到有或没有边框的相同结果。
    猜你喜欢
    • 2020-11-01
    • 2021-04-22
    • 2011-04-16
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    相关资源
    最近更新 更多