层叠上下文
大约 2 分钟
层叠上下文
层叠上下文
三维概念
HTML 文档中的元素存在于三个维度中:x 轴(水平)、y 轴(垂直)、z 轴(深度)。

层叠上下文的创建
层叠上下文是一个三维概念,表示元素在 z 轴上“高人一等”。创建方法包括:
- 根元素 HTML 自带层叠上下文。
- 设置 position 为非 static 且 z-index 为具体数值。
- CSS3 新属性也可创建层叠上下文。
示例
<div class="one"></div>
<div class="two"></div>div {
width: 200px;
height: 200px;
}
.one {
background-color: red;
position: relative;
z-index: 1;
}
.two {
background-color: blue;
margin-top: -100px;
}
层叠等级与层叠顺序
概念
- 层叠等级:在同一层叠上下文中,层叠等级越大,元素越靠前。
- 层叠顺序:具体规则决定层叠等级。

不同上下文的比较
如果元素不在同一层叠上下文中,比较其所在上下文的层叠等级。
实战案例
示例 1
<div class="one">
<div class="item" style="background-color: black; z-index: 99;"></div>
</div>
<div class="two">
<div class="item" style="background-color: pink; top: 50px; z-index: 1;"></div>
</div>.one {
background-color: red;
position: relative;
z-index: 1;
}
.two {
background-color: blue;
position: relative;
z-index: 2;
}two 的层叠等级高于 one,因此 two 的子元素覆盖 one 的子元素。
示例 2
<div class="box1">
<div class="child1"></div>
</div>
<div class="box2">
<div class="child2"></div>
</div>.box1, .box2 {
position: relative;
z-index: 0;
}box1 和 box2 产生各自的层叠上下文,child2 覆盖 child1 因为在 DOM 中后者覆盖前者。
CSS3 属性对层叠上下文的影响
以下属性可创建层叠上下文:
- display: flex|inline-flex 且子元素 z-index 非 auto
- opacity 非 1
- transform 非 none
- 其他属性如 mix-blend-mode, filter, isolation, will-change, -webkit-overflow-scrolling
示例
<div class="box">
<div class="parent">
parent
<div class="child">child</div>
</div>
</div>.box {
display: flex;
}
.parent {
width: 200px;
height: 100px;
background: #168bf5;
z-index: 1;
}
.child {
width: 100px;
height: 200px;
background: #32d19c;
position: relative;
z-index: -1;
}parent 变为层叠上下文,child 在 parent 上面。
总结
- 层叠上下文:元素在 z 轴上的层叠关系。
- 层叠等级:同一上下文中,层叠等级越大,元素越靠前。
- 层叠顺序:决定层叠等级的规则。
