不使用 z-index 屬性進行堆疊

z-index 屬性未在任何元素上指定時,元素將按以下順序堆疊(從下到上)

  1. 根元素的背景和邊框。
  2. 後代非定位元素,按 HTML 中出現的順序。
  3. 後代定位元素,按 HTML 中出現的順序。

請參閱 定位型別,瞭解定位元素和非定位元素的解釋。

請記住,當order 屬性更改 flex 容器中“HTML 中出現的順序”的渲染時,它也會類似地影響堆疊上下文的順序。

示例

在此示例中,DIV #1 到 DIV #4 是定位元素。DIV #5 是靜態的,因此繪製在其他四個元素下方,即使它在 HTML 標記中出現較晚。

HTML

html
<div id="abs1" class="absolute">
  <strong>DIV #1</strong><br />position: absolute;
</div>
<div id="rel1" class="relative">
  <strong>DIV #2</strong><br />position: relative;
</div>
<div id="rel2" class="relative">
  <strong>DIV #3</strong><br />position: relative;
</div>
<div id="abs2" class="absolute">
  <strong>DIV #4</strong><br />position: absolute;
</div>
<div id="sta1" class="static">
  <strong>DIV #5</strong><br />position: static;
</div>

CSS

css
strong {
  font-family: sans-serif;
}

div {
  padding: 10px;
  border: 1px dashed;
  text-align: center;
}

.static {
  position: static;
  height: 80px;
  background-color: #ffc;
  border-color: #996;
}

.absolute {
  position: absolute;
  width: 150px;
  height: 350px;
  background-color: #fdd;
  border-color: #900;
  opacity: 0.7;
}

.relative {
  position: relative;
  height: 80px;
  background-color: #cfc;
  border-color: #696;
  opacity: 0.7;
}

#abs1 {
  top: 10px;
  left: 10px;
}

#rel1 {
  top: 30px;
  margin: 0px 50px 0px 50px;
}

#rel2 {
  top: 15px;
  left: 20px;
  margin: 0px 50px 0px 50px;
}

#abs2 {
  top: 10px;
  right: 10px;
}

#sta1 {
  background-color: #ffc;
  margin: 0px 50px 0px 50px;
}

結果

另請參閱