如果你不是一名csser新手,想必你对z-index的用法应该有个大致的了解了吧,z-index可以控制定位元素在垂直于显示屏方向(Z 轴)上的堆叠顺序,本文不去讲述基本的API如何使用,而是去更深入的了解z-index是如何工作的,使用z-index的时候有哪些问题,以及z-index在日常开发中的使用。
下面我们通过一个例子来引入今天的正文,代码示例:
一、z-index 黄金法则及stack context
1) 一个box和它的父亲有相同的堆叠级别(stack level),除非该box被通过z-index属性赋予了不同的stack level;
2) z-index属性只适应于position属性为relative、absolute、fixed的元素对象;
3) 给一个被定位(positioned)元素设置小于1的opacity属性值,意味着创建了一个堆叠上下文(stack context),就像给该元素增加了一个z-index值;
4) 对于一个被positioned box,如果指定了z-index属性,意味着:
->该box的stack level 在当前的stack context中;
->该box建立了个本地stack context;
5) 如果box没有指定z-index,元素将被按下面的顺序堆叠(stacked)(从后到前):
-> 正常流中的boxes,根据在源代码中的序列;
-> 浮动boxes;
-> computed后display属性值为inline/inline-block/inline-table的boxes;
-> positioned boxes 和boxes 设置opacity值小于1,根据在源代码中的序列;
因此,当我们给一个positioned元素设置了z-index时,我们做了两件事:
1) 该元素与在它前面或者后面的元素共享着相同的stack context,这也就是我们改变z-index的值,元素会移动其他元素前后者后的原因。
2) 为该元素内的任何元素创建了一个新的stack context,一旦你创建了一个stack context,内部的任何有(stack context)的任何层都会停留在这个stack context。
通过上述的黄金法则,也许你已经知道上面那个问题的答案了。在黄金法则里,我们提到了个新名词“stack context”,下面我们通过一个实例来介绍它:
注意:如果你增加z-index的值,是不能使用em位于h1之上的。如果你想一个context的元素位于另一个context中的元素之上,你必须提升整个context或者设置它们为相同的context。
下面是两种解决方案:
方案一:
那么创建stack context的方式有哪些?
1) When an element is the root element of a document (theelement)
2) When an element has a position value other than static and a z-index value other than auto
3) When an element has an opacity value less than 1
Update: In addition to opacity, several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.
In WebKit, styling a box with position:fixed or -webkit-overflow-scrolling:touch implicitly creates a stacking context, just like adding a z-index value.
Also, be aware of these CSS3 “triggers”:
transform != none
transform-style: preserve-3d
filter != none
clip-path, mask
Lastly, even though a relatively positioned element without a z-index set does not establish a stacking context…
A common IE bug, often seen in drop-down menus, is that any relatively positioned element that has haslayout set to true establishes a stacking context.
One may visualize this bug by setting [A] and [B] to position:relative, while [a] gets position:relative; z-index:1.
Now, dragging [A] under [B] hides [a] – in Internet Explorer, that is. Any positioned child with a z-index is caught by this wrong stacking context of its parent.