【问题标题】:CSS moving a div vertically downCSS垂直向下移动一个div
【发布时间】:2017-02-25 03:47:19
【问题描述】:

我试图将另一个 div 中的 div 向下移动一点,但是当我使用时

margin-top: 10px;

它在顶部形成一个白色间隙。这是html:

<div id="topb">
    <div id="selection">

    </div>
</div>

这是 CSS:

#topb {
    background: url(images/tomato-background.jpg) no-repeat fixed;
    background-size: cover;
    height: 100%;
    width: 101%;
    margin-left: -10px;
}

#selection {
    background-color: #4d4d4d;
    width: 60%;
    height: 500px;
    margin: auto;
    margin-top: 40px;
}

这是网站的截图:

【问题讨论】:

  • 看起来您在#selection 中有 40px 的边距顶部。您的 10px 边距顶部在哪里?

标签: html css


【解决方案1】:

移除#selection 中的margin-top 样式,并将padding-top 应用到#topb

【讨论】:

  • 什么都不做。字面上地。看起来像这样:imgur.com/a/eOfPh
  • 确实如此。错误:) 我已经编辑过了。不管怎样,你的问题已经解决了,太好了!
【解决方案2】:

这是一个“折叠边距”问题。 在这个问题中已经回答了: Why would margin not be contained by parent element?

您必须将父 div 更改为 (1) 添加边框,(2) 绝对位置,(3) 显示为内联块,(4) 溢出自动。

更多详情请参考发布的链接。

【讨论】:

    【解决方案3】:

    也许您可以通过添加padding-top:10px; 来修改父元素,而不是修改子元素。

    【讨论】:

      【解决方案4】:

      为此,您可以使用position: absolute。代码如下:

      #topb {
          background: url(images/tomato-background.jpg) no-repeat fixed;
          background-size: cover;
          height: 100%;
          width: 101%;
          margin-left: -10px;
      }
      
      #selection {
          background-color: #4d4d4d;
          width: 60%;
          height: 500px;
          margin: auto;
          position: absolute;
          top: 40px;  /*This is where it is changed as well as the line above*/
      }

      希望对您有所帮助!我认为填充仍然会留下背景,所以这是一个更好的主意。

      【讨论】:

        【解决方案5】:

        这是工作中的fiddle,希望对您有所帮助。

        position:absolute;
        position:relative;
        

        【讨论】:

          【解决方案6】:

          这是因为当你在另一个块元素内有一个块元素(显示:块)时,边距会塌陷。它只会被认为是最大的边距。

          因此,在您的示例中,它只会考虑其中一个边距(40 像素)。 See reference about collapsing margins.

          有一些解决方法。任意选择:

          1. 内部组件使用padding 而不是margin
          2. 更改display 类型。例如display: inline-block
          3. 使用absolute定位。

          【讨论】:

            猜你喜欢
            • 2013-04-01
            • 1970-01-01
            • 2015-06-05
            • 1970-01-01
            • 1970-01-01
            • 2014-01-11
            • 1970-01-01
            • 2010-11-07
            • 1970-01-01
            相关资源
            最近更新 更多