情况如下:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
text-align: right;
background: green;
animation: animate 2s infinite alternate linear;
}
@keyframes animate {
from {
margin-top: 10px;
}
to {
margin-top: -40px;
}
}<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
发生什么事了?
如您所见,我们有两个div,没有任何复杂的样式(简单的背景色)。我正在通过应用一个负div来使第二个margin-top与第一个重叠。我希望看到一个完全重叠另一个,但事实并非如此。第二个div在第一个内容和背景之间滑动,对我来说这是一个奇怪的行为。
动画在这里没有什么用,我只是用它来更好地展示行为。我们只需在没有动画的情况下添加负值,我们就会得到同样的结果:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
margin-top:-10px;
text-align: right;
background: green;
}<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
所以我的问题是:为什么要这样做?
顺便说一句,我们都知道CSS有一些棘手的东西,当我们第一次面对它们时,我们不会怀疑它们(比如边缘崩溃,背景从身体传播到html,空格问题等等)。但它们在某个地方得到了明确的解释,我希望找到一种官方资源,使我能够清楚地理解这一点,而不仅仅是得到“也许发生这件事是因为.”、“我怀疑这与.有关”、“我认为这与.有关”等。
我对的看法/解释
我认为像文本这样的内容比背景和其他视觉样式更重要,所以当我们有重叠时,我们把所有的文本放在顶部,其他的样式放在底部,我们决定每个组内的顺序,然后打印结果。
下面是一个更复杂的例子:
body {
margin: 0;
background: pink;
color: #fff;
}
div {
font-size: 39px;
line-height: 28px;
margin-bottom: -20px;
font-weight: bold;
}
body :nth-child(1) {
background: red;
border:3px solid brown;
}
body :nth-child(2) {
background: blue;
border:3px solid yellow;
color: #000;
}
body :nth-child(3) {
background: green;
border:3px solid orange;
}<div>
some content
</div>
<div>
other content
</div>
<div>
more content
</div>
我们可以清楚地看到,可视堆栈如下(从下到上开始):
重要注意事项:在回答之前,请注意,我并不是在寻找解决这个问题的方法,也不是为了避免这个问题。只要简单地添加position:relative,行为就会消失,我们可以使用z-index来决定堆叠。我想了解为什么会发生这种事。
发布于 2018-02-11 12:08:45
这是因为等级..。我会再解释一下.
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
margin-top:-10px;
text-align: right;
background: green;
}<div class="box">
some content
</div>
<div class="bottom">
other content
</div>
在这个例子中,我们的层次结构如下所示:
.box
.box content
.bottom
.bottom content因此,现在,如果您不通过position: relative,那么它将使用正常的层次结构的HTML,而不检查div.
您已经在.box和.bottom上实现了背景,所以在本例中,当您将margin-top添加到.bottom时:
.bottom和.box具有相同的水平层次位置,但.bottom具有较大的垂直度,因此会重叠.box背景。.bottom content和.box content的位置比.bottom和.box要大,所以它们都会重叠。.bottom content将重叠.box contenthttps://stackoverflow.com/questions/48731110
复制相似问题