我有一个包含另一个div(子)的div(父)。Parent是body中的第一个元素,没有特定的CSS样式。当我设置

.child
{
    margin-top: 10px;
}

最终的结果是我的子的顶部仍然与父对齐。我的父结点向下移动10px,而不是子结点向下移动10px。

我的DOCTYPE被设置为XHTML Transitional。

我错过了什么?

编辑1 我的父母需要有严格定义的尺寸,因为它有一个背景,必须显示在它下面从上到下(像素完美)。所以不能在上面设置垂直边距。

编辑2 这种行为在FF、IE和CR上都是一样的。


当前回答

如果合适的话,使用top而不是margin-top是另一种可能的解决方案。

其他回答

父元素不能为空,至少要放 在子元素之前。

在我知道正确答案之前,我找到了另一个解决方案,即向父元素添加透明边框。

你的盒子将使用额外的像素…

.parent {
    border:1px solid transparent;
}

虽然所有的答案都解决了问题,但它们都伴随着权衡/调整/妥协,比如

floats, You have to float elements border-top, This pushes the parent at least 1px downwards which should then be adjusted with introducing -1px margin to the parent element itself. This can create problems when parent already has margin-top in relative units. padding-top, same effect as using border-top overflow: hidden, Can't be used when parent should display overflowing content, like a drop down menu overflow: auto, Introduces scrollbars for parent element that has (intentionally) overflowing content (like shadows or tool tip's triangle)

这个问题可以通过使用CSS3伪元素来解决,如下所示

.parent::before {
  clear: both;
  content: "";
  display: table;
  margin-top: -1px;
  height: 0;
}

https://jsfiddle.net/hLgbyax5/1/

这是正常的行为(至少在浏览器实现中)。边距不会影响子元素相对于父元素的位置,除非父元素有边距,在这种情况下,大多数浏览器会将子元素的边距添加到父元素的边距中。

为了得到你想要的行为,你需要:

.child {
    margin-top: 0;
}

.parent {
    padding-top: 10px;
}

.child中包含的元素的边缘正在折叠。

<html>
<style type="text/css" media="screen">
    #parent {background:#dadada;}
    #child {background:red; margin-top:17px;}
</style>
<body>
<div id="parent">

    <p>&amp;</p>

    <div id="child">
        <p>&amp;</p>    
    </div>

</div>
</body>
</html>

在这个例子中,p从浏览器默认样式接收一个边距。浏览器默认的字体大小通常是16px。通过在#child上设置超过16px的顶部边距,你开始注意到它的位置移动。