[TOC]
## 概述
層疊上下文是HTML元素的三維概念,這些HTML元素在一個假象的相對于面向(電腦屏幕的)視窗或網頁的用戶的z軸上延伸,HTML元素依據其自身屬性按照優先級順序占用層疊上下文的空間。
<br>
## 創建層疊上下文
* 根元素(**HTML**)
* **z-index** 值不為 "**auto**" 的**相對/絕對定位**
* 一個 **z-index** 值不為 "auto" 的 **flex** 項(flex item),即:父元素display: flex | inline-flex
* **opacify** 屬性值小于 1 的元素
* **transform** 屬性值不為 "**none**" 的元素
* **mix-blend-mode** 屬性值不為"**normal**"的元素
* **isolation** 屬性被設置為 "**isolate**" 的元素
* **position: fixed**
* 在 **will-change** 中指定了任意CSS屬性,即使你沒有直接指定這些屬性的值
* **-webkit-overflow-scrolling** 屬性被設置"touch"的元素
在層疊上下文中,其子元素同樣也按照上面解釋的規則進行層疊,其子元素的z-index值只在父級層疊上下文中有意義。子級層疊上下文被自動視為父級層疊上下文的一個獨立單元。
<br>
## 層疊上下文的特性
* 層疊上下文的層疊水平要比普通元素高
* 層疊上下文可以阻斷元素的混合模式
* 層疊上下文可以嵌套,內部層疊上下文及其所有子元素均受制于外部的層疊上下文
* 每個層疊上下文和兄弟元素獨立,也就是當進行層疊變化或渲染的時候,只需要考慮后代元素
* 每個層疊上下文是自成體系的,當元素發生層疊的時候,整個元素被認為是在父層疊上下文的層疊順序中
<br>
## z-index
z-index可以設置成三個值:
* auto,默認值。當設置為auto的時候,當前元素的**層疊級數是0**,同時這個盒**不會**創建新的層級上下文(除非是根元素)
* 數字。指示層疊級數,可以使負值,同時無論是什么值,都會創建一個新的層疊上下文;
* inherit
除了由根元素創建的根層疊上下文以外,其它上下文是由 z-index 不為 auto 的“positioned”元素所創建。
<br>
## 層疊順序
“層疊順序”英文稱作”stacking order”. 表示元素發生層疊時候有著特定的垂直顯示順序。

**支持 z-index 的元素: 非定位元素和非flex子元素**
如果層疊上下文元素不依賴z-index數值,則其層疊順序是z-index:auto可看成 z:index: 0 級別;
如果層疊上下文元素依賴z-index數值,則其層疊順序由z-index值決定。
定位元素會層疊在普通元素的上面,其根本原因就在于:
* 元素一旦成為定位元素,其z-index就會自動生效,此時其z-index就是默認的auto,也就是0級別,根據上面的層疊順序表,就會覆蓋inline或block或float元素。
* 而不支持z-index的層疊上下文元素天然 z-index:auto 級別,也就意味著,層疊上下文元素和定位元素是一個層疊順序的,于是當他們發生層疊的時候,遵循的是“后來居上”準則。
元素發生層疊的時候,其覆蓋關系遵循下面2個準則:
* 誰大誰上:當具有明顯的層疊水平標示的時候,如識別的z-indx值,在同一個層疊上下文領域,層疊水平值大的那一個覆蓋小的那一個。
* 后來居上:當元素的層疊水平一致、層疊順序相同的時候,在DOM流中處于后面的元素會覆蓋前面的元素。
<br>
## opacity的影響
在[CSS3-color](http://www.w3.org/TR/css3-color/#transparency)中有這樣的解釋
> Since an element with opacity less than 1 is composited from a single offscreen image, content outside of it cannot be layered in z-order between pieces of content inside of it. For the same reason, implementations must create a new stacking context for any element with opacity less than 1.
由于一個 opacity 小于1的元素需要依靠這個元素以外的圖像來合成,因此它外部內容不能根據 z-index 被層疊到該元素的內容中間(子元素也會變得透明,如果存在 z-index 不為 auto 的“positioned”子元素,那么這些子元素就需要與外部元素進行層疊計算,透明部分就會有奇怪的計算結果),因此它需要創建一個新的層疊上下文,以防止外部內容對該元素的透明化內容造成影響。
那么opacity對實際的層疊會有什么影響呢?規范中這樣描述的:
>If an element with opacity less than 1 is not positioned, implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’.
>If an element with opacity less than 1 is positioned, the ‘z-index’ property applies as described in [CSS21], except that ‘auto’ is treated as ‘0’ since a new stacking context is always created. See section 9.9 and Appendix E of [CSS21] for more information on stacking contexts.
>The rules in this paragraph do not apply to SVG elements, since SVG has its own rendering model ([SVG11], Chapter 3).
>
* opacity小于1的“non-positioned”元素,它就會被當作一個z-index: 0且opacity: 1的“positioned”元素一樣,來進行層疊計算(前文規則中的第6層);
* opacity小于1的“positioned”元素,它將按照前文中z-index的層疊規則計算技術,只不過,即使z-index是auto,仍然會創建層疊上下文;
<br>
## 例子
<br>
### 父元素是否為層疊上下文
~~~
<div class="box" style="top: 50px;">
<div id="box1" style="position:relative; z-index:2;"><br>#box1 <br> z-index:2</div>
</div>
<div class="box">
<div id="box2" style="position:relative; z-index:1;"><br><br><br>#box2 <br> z-index:1</div>
</div>
.box {
position:relative;
z-index: auto;
text-align: center;
}
#box1 {width: 200px;height: 90px;border: 1px dashed #999966;background-color: #ffffcc;}
#box2 {width: 90px;height: 200px;border: 1px dashed #669966;background-color: #ccffcc;}
~~~

把 .box 中的 z-index: auto 改為 0,結果如下:

z-index: auto 所在的 div 元素是一個普通的元素,里面的兩個子元素的層疊比較就不受父級的影響,兩者直接套用層疊黃金準則,這里,兩者有著明顯不一的z-index值,因此,遵循“誰大誰上”的準則。
而z-index一旦變成數值,哪怕是0,都會創建一個層疊上下文。此時,層疊規則就發生了變化。層疊上下文的特性里面最后一條——自成體系。兩個子元素的層疊順序比較變成了優先比較其父級層疊上下文元素的層疊順序。這里,由于兩者都是z-index:0,層疊順序這一塊兩者一樣大,此時,遵循層疊黃金準則的另外一個準則“后來居上”,根據在DOM流中的位置決定誰在上面。
<br>
### CSS3與新時代的層疊上下文
**display:flex|inline-flex與層疊上下文**
要滿足兩個條件才能形成層疊上下文:
* 父級需要是display:flex或者display:inline-flex水平
* 子元素的z-index不是auto,必須是數值。
~~~
<div class="box">
<div class="container">
container
<div class="inner">Item</div>
</div>
</div>
.box { }
.container { border: 1px dashed #999966;background-color: #ffffcc; z-index: 1; }
.inner {
width: 250px;
height: 200px;
position: relative; z-index: -1; right: -150px;
border: 1px dashed #669966;background-color: #ccffcc;
}
~~~
結果如下

將 .box 加上樣式 display: flex,則變為

沒添加 display: flex; 時,container 是普通元素,負值 z-index 的層疊順序在 block 水平元素的下面
添加 display: flex后,container 擁有層疊上下文,負值 z-index 的 item 層疊順序比 作為背景的container 高
**opacity與層疊上下文**
~~~
<div class="container">
container
<div class="inner">Item</div>
</div>
.container { border: 1px dashed #999966;background-color: #ffffcc; }
.inner {
width: 250px;
height: 200px;
position: relative; z-index: -1; right: -150px;
border: 1px dashed #669966;background-color: #ccffcc;
}
~~~

.container 添加樣式 opacity: 0.7; 后:

### 不使用 z-index時堆疊順序
~~~
<br /><br />
<div id="absdiv1" class="opacity">
<br /><span class="bold">DIV #1</span>
<br />position: absolute;
</div>
<div id="reldiv1" class="opacity">
<br /><span class="bold">DIV #2</span>
<br />position: relative;
</div>
<div id="reldiv2" class="opacity">
<br /><span class="bold">DIV #3</span>
<br />position: relative;
</div>
<div id="absdiv2" class="opacity">
<br /><span class="bold">DIV #4</span>
<br />position: absolute;
</div>
<div id="normdiv">
<br /><span class="bold">DIV #5</span>
<br />no positioning
</div>
~~~
~~~
div {
font: 12px Arial;
text-align: center;
}
.bold { font-weight: bold; }
.opacity{opacity: 0.7;}
#normdiv {
height: 70px;
border: 1px dashed #999966;
background-color: #ffffcc;
margin: 0px 50px 0px 50px;
}
#reldiv1 {
height: 100px;
position: relative;
top: 30px;
border: 1px dashed #669966;
background-color: #ccffcc;
margin: 0px 50px 0px 50px;
}
#reldiv2 {
height: 100px;
position: relative;
top: 15px;
left: 20px;
border: 1px dashed #669966;
background-color: #ccffcc;
margin: 0px 50px 0px 50px;
}
#absdiv1 {
position: absolute;
width: 150px;
height: 350px;
top: 10px;
left: 10px;
border: 1px dashed #990000;
background-color: #ffdddd;
}
#absdiv2 {
position: absolute;
width: 150px;
height: 350px;
top: 10px;
right: 10px;
border: 1px dashed #990000;
background-color: #ffdddd;
}
~~~

* #5沒有定位,處于正常流,所以根據以上規則,先于#1,#2,#3,#4這些已定位元素渲染,在最下方
* #1,#2,#3,#4都是已定位元素,且未設置z-index,所以根據其在文檔中出現的順序依次被渲染
<br>
### float的層疊
~~~
<div id="abs1">
<b>DIV #1</b><br />position: absolute;
</div>
<div id="flo1">
<b>DIV #2</b><br />float: left;
</div>
<div id="flo2">
<b>DIV #3</b><br />float: right;
</div>
<br />
<div id="sta1">
<b>DIV #4</b><br />no positioning
</div>
<div id="abs2">
<b>DIV #5</b><br />position: absolute;
</div>
~~~
~~~
div {
padding: 10px;
text-align: center;
}
#abs1 {
position: absolute;
width: 150px;
height: 200px;
top: 10px;
right: 140px;
border: 1px dashed #900;
background-color: #fdd;
}
#sta1 {
height: 100px;
border: 1px dashed #996;
background-color: #ffc;
margin: 0px 10px 0px 10px;
text-align: left;
}
#flo1 {
margin: 0px 10px 0px 20px;
float: left;
width: 150px;
height: 200px;
border: 1px dashed #090;
background-color: #cfc;
}
#flo2 {
margin: 0px 20px 0px 10px;
float: right;
width: 150px;
height: 200px;
border: 1px dashed #090;
background-color: #cfc;
}
#abs2 {
position: absolute;
width: 150px;
height: 100px;
top: 130px;
left: 100px;
border: 1px dashed #990;
background-color: #fdd;
}
~~~

* #4是正常流中非定位的元素,所以先被渲染,在最底層。
* #2 #3一個左浮動,一個右浮動,接著被渲染。彼此不會因為z-index值被覆蓋。見下圖。
* #1 #5為已定位的元素,最后被渲染,當瀏覽器窗口變小時,#5在#1上面,因為HTML文檔中#5在#1后面。見下圖。

<br>
### z-index
~~~
<div id="abs1">
<b>DIV #1</b>
<br />position: absolute;
<br />z-index: 5;
</div>
<div id="rel1">
<b>DIV #2</b>
<br />position: relative;
<br />z-index: 3;
</div>
<div id="rel2">
<b>DIV #3</b>
<br />position: relative;
<br />z-index: 2;
</div>
<div id="abs2">
<b>DIV #4</b>
<br />position: absolute;
<br />z-index: 1;
</div>
<div id="sta1">
<b>DIV #5</b>
<br />no positioning
<br />z-index: 8;
</div>
~~~
~~~
div {
padding: 10px;
opacity: 0.7;
text-align: center;
}
#abs1 {
z-index: 5;
position: absolute;
width: 150px;
height: 350px;
top: 10px;
left: 10px;
border: 1px dashed #900;
background-color: #fdd;
}
#rel1 {
z-index: 3;
height: 100px;
position: relative;
top: 30px;
border: 1px dashed #696;
background-color: #cfc;
margin: 0px 50px 0px 50px;
}
#rel2 {
z-index: 2;
height: 100px;
position: relative;
top: 15px;
left: 20px;
border: 1px dashed #696;
background-color: #cfc;
margin: 0px 50px 0px 50px;
}
#abs2 {
z-index: 1;
position: absolute;
width: 150px;
height: 350px;
top: 10px;
right: 10px;
border: 1px dashed #900;
background-color: #fdd;
}
#sta1 {
z-index: 8;
height: 70px;
border: 1px dashed #996;
background-color: #ffc;
margin: 0px 50px 0px 50px;
}
~~~

<br>
### 同一層疊上下文
~~~
<div id="div1">
<br /><span class="bold">DIV #1</span>
<br />position: relative;
<div id="div2">
<br /><span class="bold">DIV #2</span>
<br />position: absolute;
<br />z-index: 1;
</div>
</div>
<br />
<div id="div3">
<br /><span class="bold">DIV #3</span>
<br />position: relative;
<div id="div4">
<br /><span class="bold">DIV #4</span>
<br />position: absolute;
<br />z-index: 2;
</div>
</div>
~~~
~~~
.bold {
font-weight: bold;
font: 12px Arial;
}
#div1,
#div3 {
height: 80px;
position: relative;
border: 1px dashed #669966;
background-color: #ccffcc;
padding-left: 5px;
}
#div2 {
opacity: 0.8;
z-index: 1;
position: absolute;
width: 150px;
height: 200px;
top: 20px;
left: 170px;
border: 1px dashed #990000;
background-color: #ffdddd;
text-align: center;
}
#div4 {
opacity: 0.8;
z-index: 2;
position: absolute;
width: 200px;
height: 100px;
top: 65px;
left: 50px;
border: 1px dashed #000099;
background-color: #ddddff;
text-align: left;
padding-left: 10px;
}
~~~

div#1 與 div#3的層級順序與 z-index: 0相同,但沒有創建層疊上下文。因此直接比較 div#2 與div#4 的 z-index 大小
<br>
若給 div#3加上 z-index: 1, div#2 z-index 改為2,div#4 z-index改為100,結果如下

div#2 與 div#3 都創建了層疊上下文且層級相同(相對于根節點),因此 div#3 在 div#2 的下面。div#4在 div#3的層級上下文中,必然會在 div#3之上,但因為 div#3 的層疊順序在 div#2 之下,不管 div#4的 z-index 為多少 都在 div#2 下。
<br>
再次對元素樣式修改
讓 div#1 和 div#3 的 z-index為1,它們在 SC0(根層疊上下文)中的層級都是1,那么它們將按照DOM樹的順序來繪制,這意味著 div#3 稍微比 div#1 高那么一點。在這兩個層疊上下文中,分別有子元素 div#2 和 div#4。此時,盡管 div#2的層級數非常大,但由于它所處的層疊上下文 SC1 在 SC3 之下,因此 div#2 不僅在 div#4 之下,還會位于 div#3 之下。

<br>
## 總結
* 元素設置了z-index后,必須將position設置為fixed、absolute或relative才回使z-index創建新的層疊上下文或生效
* 根元素擁有一個根層疊上下文
* opacity及一些其他新的CSS3屬性的設置也可能創建新的層疊上下文,這些屬性的引入讓層疊計算變得更加復雜
* 計算層疊順序時,需要先考慮元素所處的層疊上下文,層疊上下文之間的層疊關系直接決定了其元素集合之間的層疊關系(從父規則);
> 層疊上下文的層級是HTML元素層級的一個層級,因為只有某些元素才會創建層級上下文。可以這樣說,沒有創建自己的層級上下文的元素將被父層疊上下文包含
<br>
參考資料
[深入理解CSS中的層疊上下文和層疊順序 ? 張鑫旭-鑫空間-鑫生活](https://www.zhangxinxu.com/wordpress/2016/01/understand-css-stacking-context-order-z-index/)
[層疊上下文 Stacking Context - elcarim - 博客園](https://www.cnblogs.com/elcarim5efil/p/4764607.html)
[z-index堆疊規則 - starof - 博客園](https://www.cnblogs.com/starof/p/4424926.html)
[the_stacking_context](https://developer.mozilla.org/zh-CN/docs/web/guide/css/understanding_z_index/the_stacking_context)
[Stacking with floated blocks](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_and_float)
[Adding_z-index](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/Adding_z-index)
[Stacking_context_example_1](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/Stacking_context_example_1)
- 第一部分 HTML
- meta
- meta標簽
- HTML5
- 2.1 語義
- 2.2 通信
- 2.3 離線&存儲
- 2.4 多媒體
- 2.5 3D,圖像&效果
- 2.6 性能&集成
- 2.7 設備訪問
- SEO
- Canvas
- 壓縮圖片
- 制作圓角矩形
- 全局屬性
- 第二部分 CSS
- CSS原理
- 層疊上下文(stacking context)
- 外邊距合并
- 塊狀格式化上下文(BFC)
- 盒模型
- important
- 樣式繼承
- 層疊
- 屬性值處理流程
- 分辨率
- 視口
- CSS API
- grid(未完成)
- flex
- 選擇器
- 3D
- Matrix
- AT規則
- line-height 和 vertical-align
- CSS技術
- 居中
- 響應式布局
- 兼容性
- 移動端適配方案
- CSS應用
- CSS Modules(未完成)
- 分層
- 面向對象CSS(未完成)
- 布局
- 三列布局
- 單列等寬,其他多列自適應均勻
- 多列等高
- 圣杯布局
- 雙飛翼布局
- 瀑布流
- 1px問題
- 適配iPhoneX
- 橫屏適配
- 圖片模糊問題
- stylelint
- 第三部分 JavaScript
- JavaScript原理
- 內存空間
- 作用域
- 執行上下文棧
- 變量對象
- 作用域鏈
- this
- 類型轉換
- 閉包(未完成)
- 原型、面向對象
- class和extend
- 繼承
- new
- DOM
- Event Loop
- 垃圾回收機制
- 內存泄漏
- 數值存儲
- 連等賦值
- 基本類型
- 堆棧溢出
- JavaScriptAPI
- document.referrer
- Promise(未完成)
- Object.create
- 遍歷對象屬性
- 寬度、高度
- performance
- 位運算
- tostring( ) 與 valueOf( )方法
- JavaScript技術
- 錯誤
- 異常處理
- 存儲
- Cookie與Session
- ES6(未完成)
- Babel轉碼
- let和const命令
- 變量的解構賦值
- 字符串的擴展
- 正則的擴展
- 數值的擴展
- 數組的擴展
- 函數的擴展
- 對象的擴展
- Symbol
- Set 和 Map 數據結構
- proxy
- Reflect
- module
- AJAX
- ES5
- 嚴格模式
- JSON
- 數組方法
- 對象方法
- 函數方法
- 服務端推送(未完成)
- JavaScript應用
- 復雜判斷
- 3D 全景圖
- 重載
- 上傳(未完成)
- 上傳方式
- 文件格式
- 渲染大量數據
- 圖片裁剪
- 斐波那契數列
- 編碼
- 數組去重
- 淺拷貝、深拷貝
- instanceof
- 模擬 new
- 防抖
- 節流
- 數組扁平化
- sleep函數
- 模擬bind
- 柯里化
- 零碎知識點
- 第四部分 進階
- 計算機原理
- 數據結構(未完成)
- 算法(未完成)
- 排序算法
- 冒泡排序
- 選擇排序
- 插入排序
- 快速排序
- 搜索算法
- 動態規劃
- 二叉樹
- 瀏覽器
- 瀏覽器結構
- 瀏覽器工作原理
- HTML解析
- CSS解析
- 渲染樹構建
- 布局(Layout)
- 渲染
- 瀏覽器輸入 URL 后發生了什么
- 跨域
- 緩存機制
- reflow(回流)和repaint(重繪)
- 渲染層合并
- 編譯(未完成)
- Babel
- 設計模式(未完成)
- 函數式編程(未完成)
- 正則表達式(未完成)
- 性能
- 性能分析
- 性能指標
- 首屏加載
- 優化
- 瀏覽器層面
- HTTP層面
- 代碼層面
- 構建層面
- 移動端首屏優化
- 服務器層面
- bigpipe
- 構建工具
- Gulp
- webpack
- Webpack概念
- Webpack工具
- Webpack優化
- Webpack原理
- 實現loader
- 實現plugin
- tapable
- Webpack打包后代碼
- rollup.js
- parcel
- 模塊化
- ESM
- 安全
- XSS
- CSRF
- 點擊劫持
- 中間人攻擊
- 密碼存儲
- 測試(未完成)
- 單元測試
- E2E測試
- 框架測試
- 樣式回歸測試
- 異步測試
- 自動化測試
- PWA
- PWA官網
- web app manifest
- service worker
- app install banners
- 調試PWA
- PWA教程
- 框架
- MVVM原理
- Vue
- Vue 餓了么整理
- 樣式
- 技巧
- Vue音樂播放器
- Vue源碼
- Virtual Dom
- computed原理
- 數組綁定原理
- 雙向綁定
- nextTick
- keep-alive
- 導航守衛
- 組件通信
- React
- Diff 算法
- Fiber 原理
- batchUpdate
- React 生命周期
- Redux
- 動畫(未完成)
- 異常監控、收集(未完成)
- 數據采集
- Sentry
- 貝塞爾曲線
- 視頻
- 服務端渲染
- 服務端渲染的利與弊
- Vue SSR
- React SSR
- 客戶端
- 離線包
- 第五部分 網絡
- 五層協議
- TCP
- UDP
- HTTP
- 方法
- 首部
- 狀態碼
- 持久連接
- TLS
- content-type
- Redirect
- CSP
- 請求流程
- HTTP/2 及 HTTP/3
- CDN
- DNS
- HTTPDNS
- 第六部分 服務端
- Linux
- Linux命令
- 權限
- XAMPP
- Node.js
- 安裝
- Node模塊化
- 設置環境變量
- Node的event loop
- 進程
- 全局對象
- 異步IO與事件驅動
- 文件系統
- Node錯誤處理
- koa
- koa-compose
- koa-router
- Nginx
- Nginx配置文件
- 代理服務
- 負載均衡
- 獲取用戶IP
- 解決跨域
- 適配PC與移動環境
- 簡單的訪問限制
- 頁面內容修改
- 圖片處理
- 合并請求
- PM2
- MongoDB
- MySQL
- 常用MySql命令
- 自動化(未完成)
- docker
- 創建CLI
- 持續集成
- 持續交付
- 持續部署
- Jenkins
- 部署與發布
- 遠程登錄服務器
- 增強服務器安全等級
- 搭建 Nodejs 生產環境
- 配置 Nginx 實現反向代理
- 管理域名解析
- 配置 PM2 一鍵部署
- 發布上線
- 部署HTTPS
- Node 應用
- 爬蟲(未完成)
- 例子
- 反爬蟲
- 中間件
- body-parser
- connect-redis
- cookie-parser
- cors
- csurf
- express-session
- helmet
- ioredis
- log4js(未完成)
- uuid
- errorhandler
- nodeclub源碼
- app.js
- config.js
- 消息隊列
- RPC
- 性能優化
- 第七部分 總結
- Web服務器
- 目錄結構
- 依賴
- 功能
- 代碼片段
- 整理
- 知識清單、博客
- 項目、組件、庫
- Node代碼
- 面試必考
- 91算法
- 第八部分 工作代碼總結
- 樣式代碼
- 框架代碼
- 組件代碼
- 功能代碼
- 通用代碼