z-index

z-index 属性只作用在 被定位 了的元素上。所以如果你在一个 没被定位 的元素上使用z-index的话,是不会有效果的。还有就是 z-index 会创建一个 堆叠的上下文(Stacking Contexts),我们可以理解为一个层。

以下情况都会生成一个层:

  • 当一个元素位于 HTML 文档的最外层(元素)
  • 当一个元素被「定位了(postion: fixed | absolute | relative | sticky)」并且拥有一个 z-index 值(不为auto)
  • 当一个元素被设置了opacity,transforms, filters, css-regions, paged media 等属性。

同一层元素里面的顺序:

  • 层的根元素
  • 被定位了得元素并且 z-index 值为负,相同 z-index 的情况下,按照HTML元素的书写顺序排列,下面相同。
    • 没有被定位的元素。
    • 被定位的元素,并且 z-index 值为auto,元素在当前层叠上下文中的层叠级别是 0。元素不会创建新的局部层叠上下文,除非它是根元素。
    • 被定位了的元素并且 z-index 值为正。
    • 同一个层叠上下文中,层叠级别相同的两个元素,依据它们在HTML文档流中的顺序,写在后面的将会覆盖前面的。
    • 不同层叠上下文中,元素的显示顺序依据祖先的层叠级别来决定,与自身的层叠级别无关。

Stacking Context

In summary:

  • Stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts.
  • Each stacking context is completely independent of its siblings: only descendant elements are considered when stacking is processed.
  • Each stacking context is self-contained: after the element’s contents are stacked, the whole element is considered in the stacking order of the parent stacking context.

A stacking context is formed, anywhere in the document, by any element in the following scenarios:

Within a stacking context, child elements are stacked according to the same rules previously explained. Importantly, the z-index values of its child stacking contexts only have meaning in this parent.