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

.child
{
    margin-top: 10px;
}

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

我的DOCTYPE被设置为XHTML Transitional。

我错过了什么?

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

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


当前回答

我发现, 在你的.css >中,如果你设置一个div元素的显示属性为内联块,它就会修复这个问题。保证金会像预期的那样起作用。

其他回答

这对我来说很管用

.parent {
padding-top: 1px;
margin-top: -1px;
}

.child {
margin-top:260px;
}

http://jsfiddle.net/97fzwuxh/

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

玩父母显示

.parent{
     display: inline-block;
     width: 100%;
}

or

.parent{ display: flex; }

我也有这个问题,但更喜欢防止负利润率黑客,所以我放了一个

<div class=“supercontainer”></div>

周围有填充而不是边距。当然,这意味着更多的性炎,但这可能是最干净的方法来做到这一点。

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

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/