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

.child
{
    margin-top: 10px;
}

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

我的DOCTYPE被设置为XHTML Transitional。

我错过了什么?

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

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


当前回答

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

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

.parent {
    border:1px solid transparent;
}

其他回答

你可以通过在伪元素display: flex;给父母。

.parent:before {
  content: '';
  display: flex;
}

另一种方法是将父节点的display属性设置为flow-root。

.parent {
  display: flow-root;
}

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

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

防止“Div父”使用“Div子”的边距: 在父级中使用这些css:

浮动 填充 边境 溢出

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

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/