【问题标题】:Margin-top collapsing issue边距顶部折叠问题
【发布时间】:2014-06-07 02:30:26
【问题描述】:

我可能只是不了解基本的 CSS 和 HTML,但这让我非常恼火。我在“内容” div 中有一个“测试” div,我想要一个 10 像素的边距顶部而不是填充,因为我想将整个“测试”元素向下推 10 像素。 margin-top 似乎是答案,但它不是从父元素推送,而是从页面顶部推送。

* {
  margin: 0px;
  padding: 0px;
  font-family: 'Source Sans Pro', sans-serif;
}
body {
  background-color: #336699;
}
a {
  text-decoration: none;
  color: #336699;
}
#container {
  margin: 0px auto;
  width: 1000px;
}
#content {
  background-color: rgba(255, 255, 255, 1);
  margin-top: 50px;
  height: 500px;
  border-radius: 10px;
}
#test {
  background-color: red;
  margin-top: 10px;
}
<div id="container">
  <div id="content">
    <div id="test">
      test
    </div>
  </div>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您正在见证collapsing margins。只需将overflow:auto; 添加到#content

    #content {
        background-color: rgba(255, 255, 255, 1);
        margin-top: 50px;
        height: 500px;
        border-radius: 10px;
        overflow:auto;
    }
    

    jsFiddle example

    【讨论】:

      【解决方案2】:

      如果您只想将 #test 元素向下移动,则将 padding-top: 10px 添加到其父元素。

      【讨论】:

        【解决方案3】:

        设置#Container有一个位置:绝对;然后将您希望使用 margin-top 的元素设置为 position:relative

        【讨论】:

          【解决方案4】:

          您遇到了一个称为折叠 - 边距的问题。 只是为了确保您没有做错任何事情,请添加以下代码:

          *, *:after, *:before{
              box-sizing: border-box;
              margin: 0;
              padding: 0;
              font-family: 'Source Sans Pro', sans-serif;
          }
          

          这将确保您的盒子模型是正确的。 并将溢出自动添加到内容中。

          这是一个修复了你的东西的演示。

          http://codepen.io/yisera/pen/qizwt/

          【讨论】:

            猜你喜欢
            • 2017-02-17
            • 2013-05-05
            • 2010-09-11
            • 2011-02-09
            • 2017-07-27
            • 1970-01-01
            • 2017-07-09
            • 1970-01-01
            • 2018-10-30
            相关资源
            最近更新 更多