【问题标题】:CSS - Margin against MarginCSS - 保证金对保证金
【发布时间】:2018-03-30 03:35:06
【问题描述】:

我有 2 个 div 的问题 - 都呈现为块都有 15px 的边距(顶部 div 有底部边距,底部有顶部),因此我预计之间的差距是 30px 而不是 15px,这是正确的假设还是我要疯了!?

干杯 保罗

【问题讨论】:

  • 搞定了,间距为 15px jsfiddle.net/RBR79
  • 可能有很多因素导致这种情况——定位、浮动、浏览器、容器块...请发布相关的 CSS 和 HTML。 edit @thirtydot: 哦,忘了边距垂直折叠。 richinstyle.com/guides/box2.html#margin
  • @stslavik:它正在折叠边距。

标签: css


【解决方案1】:

CSS box model 定义了collapsing margins 的行为,它是所有浏览器的预期行为。

You might also find my answer to this related question to be of use.

【讨论】:

    【解决方案2】:

    两个边距都是 15px,而不是它们的总和。如果要添加它们,请改用填充。

    【讨论】:

      【解决方案3】:

      遇到了同样的问题,无法使用填充作为修复。 我已经设法用这个小技巧解决了这个问题:

      .btn {
          /* hack for a 2px margin */
          border-top: 2px #fff solid !important;
          /* this is important if you have a background-color
          and don't want to see it underneath the transparent border*/
          background-clip: padding-box;
      }
      

      请启动此 sn-p 进行演示:

      div {
        margin: 10px;
        background: rgb(48, 158, 140);
        padding: 5px 15px;
        font-weight: bold;
        color: #fff;
      }
      
      .fake-margin {
        border-top: 10px solid transparent;
        background-clip: padding-box;
      }
      <div>Margin applied is 10px on each sides</div>
      <div>the first two have only 10px between them</div>
      <div class="fake-margin">the last two have 10 + 10px</div>
      <div class="fake-margin">= 20 px</div>

      【讨论】:

        【解决方案4】:

        正确 - 但如果效果不佳,您可以尝试“填充”而不是“边距” - 这可能会产生预期的效果。

        【讨论】:

        • 内边距和边距是完全不同的东西,你不应该用一个代替另一个。
        • 填充应该只影响包含的 div。它是容器内边缘和内容外边缘之间的空间。
        • 我的印象是他想要 30 像素的空间。填充会做到这一点。感谢您的单挑团伙。
        • 我给 -1 不是因为您建议使用填充,而是因为您说 Paul 的假设是“正确的”,但它肯定不是。
        • 是的,你是对的 zzzzBov。我今天显然有点落后了 - 需要更多的 java。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多