为什么 position: fixed 不遵循堆叠上下文规则?

Why position: fixed does not follow the stacking context rules?

使用 rel 和 rel1 的 z-index 会改变堆叠位置,但即使使用更高的 z-index,fx 也永远不会在它们之上,除非在 DOM。为什么会这样?

.fx {
  position: fixed;
  height: 30px;
  width: 30px;
  background-color: pink;
  margin-top: 60px;
  margin-left: 30px;
  z-index: 10000;
}

.rel {
  z-index: 7;
  position: relative;
  height: 500px;
  width: 200px;
  background-color: red;
  margin-top: 30px;
}

.rel1 {
  z-index: 6;
  position: relative;
  height: 500px;
  width: 100px;
  background-color: black;
  margin-top: -300px;
}
<div class="rel">
</div>

<div class="rel1">
</div>

<div class="fx">
</div>

它确实遵循堆叠规则但它的位置尚未设置,您必须将位置设置为顶部:0px;

你需要给.fx位置属性:

通常是 topbottom leftright 的组合。


工作示例:

.fx {
  position: fixed;
  top: 0;
  left: 0;
  height: 30px;
  width: 30px;
  background-color: pink;
  margin-top: 60px;
  margin-left: 30px;
  z-index: 10000;
}

.rel {
  z-index: 7;
  position: relative;
  height: 500px;
  width: 200px;
  background-color: red;
  margin-top: 30px;
}

.rel1 {
  z-index: 6;
  position: relative;
  height: 500px;
  width: 100px;
  background-color: black;
  margin-top: -300px;
}
<div class="rel">
</div>

<div class="rel1">
</div>

<div class="fx">
</div>

As mdn says about position: fixed:

Its final position is determined by the values of top, right, bottom, and left.

因此您的代码将如下所示:

.fx {
  position: fixed;
  height: 30px;
  width: 30px;
  background-color: pink;
  margin-top: 60px;
  margin-left: 30px;
  z-index: 10000;
  top: 20px;
  left: 10px;
}

.rel {
  z-index: 7;
  position: relative;
  height: 500px;
  width: 200px;
  background-color: red;
  margin-top: 30px;
}

.rel1 {
  z-index: 6;
  position: relative;
  height: 500px;
  width: 100px;
  background-color: black;
  margin-top: -300px;
}
<div class="rel">
  </div>

  <div class="rel1">
  </div>

  <div class="fx">
  </div>