层叠上下文是HTML元素的三维概念,这些HTML元素在一条假想的相对于面向(电脑屏幕的)视窗或者网页的用户的z轴上延伸,HTML元素依据其自身属性按照优先级顺序占用层叠上下文的空间。css
因此一个页面中每每不单单只有一个层叠上下文(由于有不少种方式能够生成层叠上下文),在一个层叠上下文内,咱们按照层叠水平的规则来堆叠元素。html
咱们能够把触发层叠上下文的条件分为三大类:web
这就是为何,绝对定位元素在left/top等值定位的时候,若是没有其余定位元素限制,会相对浏览器窗口定位的缘由。浏览器
<style>
* {
margin: 0;
padding: 0;
}
.container {
background: pink;
height: 100vh;
}
.box {
width: 160px;
}
.box1 {
position: relative;
left: 0;
top: 0;
z-index: 1;
background: blue;
height: 160px;
}
.box2 {
position: absolute;
left: 0;
top: 0;
z-index: -1;
background: gray;
height: 180px;
}
.box3 {
position: fixed;
z-index: 0;
background: greenyellow;
left: 0;
top: 0;
height: 200px;
}
.box4 {
height: 220px;
background: orange;
}
</style>
<div class="container">
<div class="box1 box">相对定位, z-index: 1</div>
<div class="box2 box">绝对定位, z-index: -1</div>
<div class="box3 box">固定定位, z-index: 0</div>
<div class="box4 box">普通元素</div>
</div>
复制代码
<style>
* {
margin: 0;
padding: 0;
}
.box { display: flex; background: pink;}
.box > div { background-color: blue; z-index: 1; } /* 此时该div是层叠上下文元素,同时z-index生效 */
.box > div > img {
position: relative; z-index: -1; right: -150px; /* 注意这里是负值z-index */
}
</style>
<div class="box">
<div>
<img src="mm.png">
</div>
</div>
复制代码
这种状况下,基本上都是由 CSS3 中新增的属性来触发的。bash
<style>
* {
margin: 0;
padding: 0;
}
.box { background-color: blue; opacity: 0.5; }
.box>img {
position: relative;
z-index: -1;
right: -150px;
}
</style>
<div class="box">
<img src="mm.png">
</div>
复制代码
<style>
* {
margin: 0;
padding: 0;
}
.box {
background-color: blue;
transform: rotate(15deg);
}
.box>img {
position: relative;
z-index: -1;
right: -150px;
}
</style>
<div class="box">
<img src="mm.png">
</div>
复制代码
<style>
* {
margin: 0;
padding: 0;
}
.box {
background-color: blue;
mix-blend-mode: darken;
}
.box>img {
position: relative;
z-index: -1;
right: -150px;
}
</style>
<div class="box">
<img src="mm.png">
</div>
复制代码
<style>
* {
margin: 0;
padding: 0;
}
.box {
background-color: blue;
perspective: 250px;
}
.box>img {
position: relative;
z-index: -1;
right: -150px;
}
</style>
<div class="box">
<img src="mm.png">
</div>
复制代码
<style>
* {
margin: 0;
padding: 0;
}
.box {
background-color: blue;
filter: blur(5px);
}
.box>img {
position: relative;
z-index: -1;
right: -150px;
}
</style>
<div class="box">
<img src="mm.png">
</div>
复制代码
一个 DOM 元素,在不考虑层叠上下文的状况下,会按照层叠水平决定元素在 z 轴上的显示顺序,通俗易懂地讲,不一样的 DOM 元素组合在一块儿发生重叠的时候,它们的的显示顺序会遵循层叠水平的规则,而 z-index 是用来调整某个元素显示顺序,使该元素可以上浮下沉。ide
- 在同一层叠上下文中,层叠水平才有意义
- z-index的优先级最高
复制代码
note: 发布有些匆忙,有误地方后续订正。wordpress