【问题标题】:h1, h2, h3.. elements eats div marginsh1, h2, h3 .. 元素吃掉 div 边距
【发布时间】:2013-06-15 17:55:34
【问题描述】:

为什么在div中h1、h2、h3元素的边距会被忽略?

http://jsfiddle.net/TzmdZ/

<div class="col">
    <h3>This is header</h3>
</div>  
<div class="col">
    <h3>This is header</h3>
</div>

.col {
    background: gray;
    margin-bottom: 1em;
}

.col h3 {
    margin-bottom: 1em;
}

当我将 h 元素放入 div 并且其中没有其他文本时,虽然指定了 h 元素和 div 元素的底部边距,但忽略了 h 底部边距。

【问题讨论】:

  • 这是正确的行为,你想要的是给你的col 类一个padding-bottom: 1em;
  • 我不确定您要做什么...但也许您正在尝试做填充:改为检查 padding-bottom: 1em;
  • 你尝试忽略下边距设置 margin-top:-18px;在 .col css 中

标签: html css margin padding


【解决方案1】:

将边距分配给两个兄弟会导致边距在相邻的边距处折叠。

这个MDN document详细解释了情况。

块的顶部和底部边距有时会合并(折叠) 到单个边距,其大小是组合边距中最大的 进入其中,一种称为边距折叠的行为。

保证金崩溃发生在三种基本情况:

  1. 相邻的兄弟姐妹
  2. 父母和第一个/最后一个孩子
  3. 空块

【讨论】:

    【解决方案2】:

    试试这个 CSS:

    .col {
        background: gray;
        padding-bottom: 1em;
    }
    
    .col h3 {
        padding-bottom: 1em;
    }
    

    margin-bottom 更改为padding-bottom

    jsFiddle

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多