1. Stacking context
层叠上下文就是一条假想的网页面对用户的z轴上的延伸,层叠上下文中的元素根据其Stacking Level占用层叠上下文的空间。
Stacking Context通常由以下元素生成:
1. 根元素HTML
2. z-index值不是auto的定位元素(absolute,fixed,relative)
3. opacity小于1的元素
4. transform不是none的元素
5. 父元素display:flex,那么子元素会创建Stacking Context
Stacking context和Stacking Level的关系:Stacking context元素包含的子元素均含有Stacking Level,如果此子元素又生成新的Stacking context,那么
子元素所包含的子孙元素也具有Stacking Level。
下面这张图表明:
2) Stacking Order
一个Stacking context元素里面的元素要怎么布局呢?这个时候Stacking Order就登场了。有七个Stacking Level如下:
1. Background and borders — of the element forming the stacking context. The lowest level in the stack.
2. Negative Z-Index — the stacking contexts of descendants elements with negative z-index.
3. Block Level Boxes — in-flow non-inline-level non-positioned descendants.
4. Floated Boxes — non-positioned floats
5. Inline Boxes — in-flow inline-level non-positioned descendants.
6. Z-index: 0 — positioned elements. These form new stacking contexts.
7. Positive Z-index — positioned elements. The highest level in the stack.
这7个规则记住就行。
参考资料:
https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
https://tiffanybbrown.com/2015/09/css-stacking-contexts-wtf/
https://webdesign.tutsplus.com/articles/what-you-may-not-know-about-the-z-index-property--webdesign-16892