我有一个包含另一个div(子)的div(父)。Parent是body中的第一个元素,没有特定的CSS样式。当我设置
.child
{
margin-top: 10px;
}
最终的结果是我的子的顶部仍然与父对齐。我的父结点向下移动10px,而不是子结点向下移动10px。
我的DOCTYPE被设置为XHTML Transitional。
我错过了什么?
编辑1
我的父母需要有严格定义的尺寸,因为它有一个背景,必须显示在它下面从上到下(像素完美)。所以不能在上面设置垂直边距。
编辑2
这种行为在FF、IE和CR上都是一样的。
是关于保证金崩溃的。
块的顶部和底部边距有时会合并(折叠)为单个边距,其大小是单个边距中最大的(如果它们相等,则仅为其中之一),这种行为称为边距折叠。
根据具体情况,有几种解决方案。
一种解决方案是改变子节点的显示模式。
.child {
display: inline-block;
}
也很高兴知道。边距收缩不适用于柔性容器或网格容器。
.parent {
display: flex;
flex-direction: column;
}
或者使用父元素的填充而不是子元素的边缘。改变溢出或浮动属性也会有所帮助。或者绝对位置。这取决于你的布局。
虽然所有的答案都解决了问题,但它们都伴随着权衡/调整/妥协,比如
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/