前言
之前见过这么一段话:如果你花了三天解决了一个js的bug,你得感谢你自己很厉害。但是如果你花了三天解决了一个CSS的bug,那你得感谢老天爷!
步入正题,今天来说一下CSS里的层叠上下文。
什么是层叠上下文
层叠上下文属于CSS视觉格式化模型中的一部分,它是一块区域,由某一个元素创建,规定了该区域中的元素在Z轴上的排列顺序。
官方描述:渲染树被绘制到画布上的顺序是根据层叠上下文来描述的。层叠上下文可以包含更多的层叠上下文,每个盒子只属于一个层叠上下文。
层叠顺序
“层叠顺序”表示元素发生层叠时会按照特定的排列规则在Z轴上垂直显示。由此可见,元素在相互层叠时遵循特定的规则。
创建层叠上下文
层叠上下文的产生,一般是由一些特定的CSS属性创建,一般有3种方法。
-
html 元素,本身自带层叠上下文,称之为“根层叠上下文”
-
z-index 属性为数值的定位元素
-
其他CSS3中的属性:
元素的opacity属性值不是1;
元素的transform属性值不是none;
元素filter属性值不是none;
元素的isolation属性值是isolate; (这个属性是专门用来创建新的层叠上下文的)
mix-blend-mode属性值不是none;
will-change指的属性值为上面任意一个;
例子
以z-index、transform、opacity为例,展示各种元素之间的层叠关系。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.container {
width: 300px;
height: 300px;
background-color: #0af;
border: 10px solid #000;
position: absolute;
left: 200px;
top: 200px;
z-index: auto;
}
.item1 {
width: 200px;
height: 200px;
background-color: #f00;
position: absolute;
left: -100px;
top: -100px;
z-index: -100;
}
.item2 {
width: 200px;
height: 200px;
background-color: #0f0;
}
.item3 {
width: 200px;
height: 200px;
background-color: #00f;
float: left;
margin-left: 50px;
margin-top: 50px;
}
.item4 {
background-color: #ff0;
border: 3px solid #f0f;
margin-left: -200px;
}
.item5 {
width: 200px;
height: 200px;
background-color: #0ff;
position: absolute;
left: 100px;
top: 100px;
z-index: 0;
}
.item6 {
width: 200px;
height: 200px;
background-color: #f40;
position: absolute;
left: 150px;
top: 150px;
z-index: 10;
}
.item7 {
width: 200px;
height: 200px;
background-color: rgb(59, 45, 173);
opacity: 0.9;
margin-top: -60px;
}
.item8 {
width: 200px;
height: 200px;
background-color: rgb(218, 38, 212);
transform: translateZ(100000px);
margin-top: -50px;
margin-left: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="item1">z-index = -100</div>
<div class="item3">浮动元素</div>
<div class="item2">块级元素</div>
<span class="item4">这是行级元素</span>
<span class="item5">z-index = 0</span>
<span class="item6">z-index > 0</span>
<div class="item8">transform</div>
<div class="item7">opacity</div>
</div>
</body>
</html>