【问题标题】:Adjusting the margin-top of a div inside of a container div pushes both the inner div and container div down from body调整容器 div 内部 div 的 margin-top 会同时将内部 div 和容器 div 从主体向下推
【发布时间】:2012-01-21 17:10:52
【问题描述】:

我觉得这一定是我做了一些愚蠢的事情,但我想不通。 Here's a demo page showing my problem.页面来源:

<html>
<head>
    <title>demo</title>
    <style type='text/css'>
        body{
            margin: 0px;
            padding: 0px;
        }
        #container{
            height: 100%;
            background-color: black;
        }
        #logo{
            margin: 25px auto auto auto;
            width: 360px;
            height: 45px;
            background-color: goldenrod;
        }
    </style>
</head>
<body>
    <div id='container'>
        <div id='logo'>
            <p>logotext.</p>
        </div>
    </div>
</body>
</html>

因此,您调整页边距的上限值越多,#logo 和 #container 都被拖到页面的下方。 #container 应该保持不变,#logo 应该在页面下方移动。

【问题讨论】:

  • 这是给测试人员的一个小提琴。在#logo 上调整 25px 的边距,并注意黑条也如何向下移动页面。 jsfiddle.net/bzVgV/1

标签: css html margin


【解决方案1】:

这是由折叠边距引起的。如果两个元素有接触的边距,则边距合并。对此here 有很好的解释。转到名为Collapsing Margins Between Parent and Child Elements 的部分。

这里有三种不同的解决方案。

一种是在容器中添加overflow: auto。这会改变 BCF(块格式化上下文)。此技术在here 中有更详细的描述。

#container {
    height: 100%;
    background-color: black;
    /* Add oveflow auto to container */
    overflow: auto;
}

http://jsfiddle.net/bzVgV/20/

第二个是在容器上使用填充而不是徽标上的边距。这会排除等式的余量。

#container {
    height: 100%;
    background-color: black;
    /* Use padding on container instead of margin on logo */
    padding-top: 30px;
}

http://jsfiddle.net/bzVgV/18/

最终的解决方案是让边距不再接触。您可以通过向父级添加 1px 内边距来做到这一点。

#container {
    height: 100%;
    background-color: black;
    /* Now margins of container and logo won't touch */
    padding-top: 1px;
}

http://jsfiddle.net/bzVgV/21/

【讨论】:

  • 折叠边距是我见过的最奇怪的事情。但很高兴知道到底发生了什么。感谢您的帮助!
  • 为了让你的答案更完整,浮动子元素也不存在这个问题。虽然这在此处不适用,因为将 margin-left 和 margin-right 设置为 auto!
  • 为什么 HTML/CSS 会这样做?如果它只是按照自己的想法去做会更好...有谁知道为什么要这样设计?
猜你喜欢
  • 2013-08-26
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多