不使用 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: #ffffcc;
  border-color: #999966;
}

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

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

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

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

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

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

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

結果

另見