使用 z-index
本指南的第一篇文章《不使用 z-index
属性的堆叠》解释了堆叠是如何默认排列的。如果你想创建自定义的堆叠顺序,你可以在定位元素上使用 z-index
属性。
z-index
属性可以指定一个整数值(正数、零或负数),它表示元素沿假想 z 轴的位置。如果你不熟悉“z 轴”这个术语,可以想象页面是一叠图层,每个图层都有一个数字。图层按数字顺序渲染,数字越大越靠上(X 表示任意正整数)。
图层 | 描述 |
---|---|
最底层 | 离观察者最远 |
图层 -X | 具有负 z-index 值的图层 |
图层 0 | 默认渲染层 |
图层 X | 具有正 z-index 值的图层 |
顶层 | 离观察者最近 |
备注
- 当没有指定
z-index
属性时,元素会在默认渲染层(图层 0)上渲染。 - 如果多个元素共享相同的
z-index
值(即它们位于同一层),则适用《不使用z-index
属性的堆叠》一节中解释的堆叠规则。
示例
在此示例中,图层的堆叠顺序使用 z-index
进行了重新排列。由于 DIV #5 不是定位元素,其 z-index
没有效果。
HTML
html
<div id="abs1">
<strong>DIV #1</strong>
<br />position: absolute; <br />z-index: 5;
</div>
<div id="rel1">
<strong>DIV #2</strong>
<br />position: relative; <br />z-index: 3;
</div>
<div id="rel2">
<strong>DIV #3</strong>
<br />position: relative; <br />z-index: 2;
</div>
<div id="abs2">
<strong>DIV #4</strong>
<br />position: absolute; <br />z-index: 1;
</div>
<div id="sta1">
<strong>DIV #5</strong>
<br />no positioning <br />z-index: 8;
</div>
CSS
css
div {
padding: 10px;
opacity: 0.7;
text-align: center;
}
strong {
font-family: sans-serif;
}
#abs1 {
z-index: 5;
position: absolute;
width: 150px;
height: 350px;
top: 10px;
left: 10px;
border: 1px dashed #990000;
background-color: #ffdddd;
}
#rel1 {
z-index: 3;
height: 100px;
position: relative;
top: 30px;
border: 1px dashed #669966;
background-color: #ccffcc;
margin: 0px 50px;
}
#rel2 {
z-index: 2;
height: 100px;
position: relative;
top: 15px;
left: 20px;
border: 1px dashed #669966;
background-color: #ccffcc;
margin: 0px 50px;
}
#abs2 {
z-index: 1;
position: absolute;
width: 150px;
height: 350px;
top: 10px;
right: 10px;
border: 1px dashed #990000;
background-color: #ffdddd;
}
#sta1 {
z-index: 8;
height: 70px;
border: 1px dashed #999966;
background-color: #ffffcc;
margin: 0px 50px;
}