堆叠上下文
堆叠上下文也叫层叠上下文(stack context),它是一块区域,这块区域由某个元素创建,它规定了该区域中的内容在Z轴上排列的先后顺序。
创建堆叠上下文的元素
- html元素(根元素)
- 设置了z-index(非auto)数值的定位元素
同一个堆叠上下文中元素在Z轴上的排列
从后到前的排列顺序:
-
创建堆叠上下文的元素的背景和边框
-
堆叠级别(z-index, stack level)为负值的堆叠上下文
2.1 例子:
<style>
html {
background: lightblue;
}
.container {
background: #008c8c;
width: 200px;
height: 200px;
z-index: 0;
}
.item {
width: 100px;
height: 100px;
background: red;
z-index: -1;
}
</style>
<div class="container">
<div class="item"></div>
</div>
-
非定位的常规流块盒
3.1 非定位:position为static;
-
非定位的浮动盒子
-
非定位的常规流行盒
-
任何 z-index 是 auto 的定位子元素,以及 z-index 是 0 的堆叠上下文
6.1
<!DOCTYPE html>
<html lang="en">
<head>
<style>
html {
background: lightblue;
}
.container {
background: #008c8c;
width: 200px;
height: 200px;
position: relative;
margin: 50px;
}
.item {
width: 500px;
height: 100px;
background: red;
z-index: -1;
position: absolute;
left: -30px;
top: -30px;
}
.normal {
width: 200px;
height: 400px;
background: chocolate;
margin-top: -350px;
}
.float {
width: 200px;
height: 200px;
background: brown;
float: left;
margin-left: 100px;
margin-top: -100px;
}
</style>
</head>
<body>
<p style="background: lightyellow">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque suscipit ullam nam corporis at placeat, tempore
tenetur? Impedit, aliquid provident officiis aspernatur ea pariatur optio! Laudantium dolor voluptatibus
explicabo quae?
</p>
<div class="container">
<div class="item"></div>
</div>
<div class="float"></div>
<div class="normal"></div>
</body>
</html>
- 堆叠级别为正值的堆叠上下文
注意:每个堆叠上下文,独立于其他堆叠上下文,它们之间不能相互穿插。
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html {
background: lightblue;
}
.c1 {
position: relative;
z-index: 0;
width: 200px;
height: 200px;
background: #008c8c;
}
.c2 {
position: absolute;
z-index: -1;
width: 200px;
height: 200px;
background: chocolate;
left: 100px;
top: 100px;
}
.item1{
position: absolute;
width: 100px;
height: 100px;
}
.item1{
right: -50px;
bottom: -50px;
}
</style>
</head>
<body>
<div class="c1">
<div class="item1" style="background: red; z-index: -9999;"></div>
</div>
<div class="c2">
<div class="item1" style="background: rgb(145, 0, 0); z-index: 9999;"></div>
</div>
</body>
</html>