没有 z-index 的相对定位会导致重叠

Relative positioning without z-index causes overlapping

我创建了两个兄弟 div 并在最后一个上应用了负边距,但是当我将 position: relative 添加到第一个时,它与下一个兄弟 div 重叠:

.box {
  width: 100px;
  height: 100px;
}

.box-1 {
  position: relative;
  background: orange;
}

.box-2 {
  margin-top: -50px;
  background: yellowgreen;
}
<div class="box box-1">box-1</div>
<div class="box box-2">box-2</div>

然而,MDN表示

positioned (absolutely or relatively) with a z-index value other than "auto" will create a new stacking context.

所以我猜不是堆叠上下文导致了重叠,知道这是怎么发生的吗?

重叠是由您的 CSS

中的 margin-top: -50px; 造成的

这里有一个不错的解释:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/Stacking_without_z-index

Standard blocks in the normal flow, without any positioning property, are always rendered before positioned elements, and appear below them, even if they come later in the HTML hierarchy.

非定位元素总是在 显式定位元素之前呈现。这意味着通过将 position: relative 应用于 'box-1',它会在 之后呈现 'box-2' 并因此出现在它上面。

Standard blocks in the normal flow, without any positioning property, are always rendered before positioned elements, and appear below them, even if they come later in the HTML hierarchy.

例子是

.absolute {
    position: absolute;
    background:purple;
    left: 80px;
}

.relative {
    position: relative;
    left:50px;
    background:yellow;
    top:-50px;
}

div {
    width:100px;
    height:100px;
    border: 1px dashed #999966;
    background:blue;
}
<div class="absolute">absolute</div>
<div>normal</div>
<div class="relative">relative</div>
<div>normal</div>

relative 有一点很酷,就是它仍然被认为是在原来的位置,即使它在您使用 left, right, top, bottom 时被移动了。如果您使用边距来定位元素,则容器的边界也会随之移动。这可以是 seen using the same example above but changing the relative position to use margining. Reference to relative positioning