【问题标题】:Margin-top not working [duplicate]边距顶部不起作用[重复]
【发布时间】:2012-07-26 22:10:40
【问题描述】:

当我使用左边距时,它可以工作。但边距顶部不起作用。有谁知道为什么 on 有效而另一个无效?

HTML代码

<div id="footer"> <!-- BEGIN FOOTER -->
<p class="copyright"> Copyright © </p>
</div> <!-- END FOOTER -->

CSS

#footer {

background-image: url(../website/images/footer.png);
width: 1200px;
height: 100px;

}

p.copyright {

margin-top: 10px;
margin-left: 120px;

}

【问题讨论】:

  • 页脚上方是什么?漂浮的东西?定位?可能浮标还没有清除?
  • 这里可以正常工作:jsfiddle.net/qyUMC。能多给点代码吗
  • @Enve 不行:jsfiddle.net/nFJgV
  • 你的 p 标签默认有边距,而不是使用 margin-top:20 或其他东西作为顶部可能会起作用
  • @Enve 的示例有效,实际上他自己的标记工作得很好,除非直到他的意思是即使父 div 也被移到下面

标签: html css


【解决方案1】:

这称为边距折叠。当一个块元素是另一个块元素的子元素时,就会发生这种情况。这里有几种方法可以解决这个问题。

1- 给元素添加边框

2- 添加 1px 的内边距

3- 更改位置属性。绝对和相对定位框的边距不会塌陷。

我最近写了一篇关于这方面的博客文章以了解更多信息,请参阅 here

【讨论】:

【解决方案2】:

试试this

#footer {
    background-image: url(../website/images/footer.png);
    width: 1200px;
    height: 100px;
    position:absolute;
}

p.copyright {
    background-color:red;
    margin-top: 10px;
    margin-left: 120px;
}​

【讨论】:

    【解决方案3】:

    试试这个:-

      #footer {
        background-image: url(../website/images/footer.png);
        width: 1200px;
        height: 100px;
        overflow:hidden; // add overflow
      }
        
      p.copyright {
        margin-top: 10px;
        margin-left: 120px;
      }
    

    【讨论】: