層疊上下文是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