http://www.zhangxinxu.com/wordpress/2016/01/understand-css-stacking-context-order-z-index/
概念
層疊上下文,英文稱作”stacking context”. 是HTML中的一個(gè)三維的概念。層疊水平和CSS的z-index屬性不能混為一談,某些情況下z-index確實(shí)可以影響層疊水平。但是,只限于定位元素以及flex盒子的孩子元素;而層疊水平所有的元素都存在。
在默認(rèn)情況下(是在css3之前)
inline-block盒子>float盒子>block盒子=(z-index:auto)>負(fù)z-index
以上可以理解為,裝飾屬性在最下,布局屬性在上,內(nèi)容屬性在最上面。
display:flex|inline-flex與層疊上下文
<pre><div class="box">
<div>
<img src="mm1.jpg">
</div>
</div></pre>
<pre>
.box { }
.box > div {
background-color: blue; z-index: 1;
} /* 此時(shí)該div是普通元素,z-index無效 /
.box > div > img {
position: relative; z-index: -1; right: -150px;
} / 注意這里是負(fù)值z(mì)-index */
</pre>
這里只看Img的負(fù)z-index,所以在默認(rèn)盒子下面
<pre><div class="box">
<div>
<img src="mm1.jpg">
</div>
</div></pre>
<pre>
.box { display:flex }
.box > div {
background-color: blue; z-index: 1;
} /* 此時(shí)該div是層疊上下文,z-index為1 /
.box > div > img {
position: relative; z-index: -1; right: -150px;
} / 注意這里是負(fù)值z(mì)-index */
</pre>
這里都是層疊了,父級(jí)div成了層疊背景。
opacity與層疊上下文
當(dāng)opacity小于1時(shí),就變成層疊上下文。遵循上面規(guī)則,父級(jí)div成了層疊背景
** transform與層疊上下文**
添加transform,也會(huì)變成層疊上下文
總結(jié):
- 首先關(guān)心的是是否是層疊元素,如果是層疊元素,就按照層疊規(guī)則(圖)作比較。不是層疊元素的,就在圖中默認(rèn)情況。
- 在css3,以下會(huì)讓元素變成層疊元素:
- opacity小于1
- 新的filter屬性
- transform
- 父級(jí)元素為flex屬性
- 比大小值,同級(jí)看順序。