堆叠顺序

从下面这些例子里面可以看出来,各属性及元素的堆叠顺序。

background 高于负 z-index :

See the Pen The stacking order: background vs negative z-index by dsphoebe (@dsphoebe) on CodePen.

backgroundborder 层下面,就像 Photoshop 里面,新建一个文件,默认的第一个图层而且是不可编辑图层就是带背景的图层,想通的可以这样理解为,设计 CSS 的人也是认为背景是最下面的,这大概是个常识吧。

border 高于 background

See the Pen The stacking order by dsphoebe (@dsphoebe) on CodePen.

内联元素高于 border

See the Pen The stacking order: border vs inline/text by dsphoebe (@dsphoebe) on CodePen.

浮动元素高于 border

See the Pen The stacking order: border vs float by dsphoebe (@dsphoebe) on CodePen.

内嵌元素高于浮动元素:

See the Pen The stacking order: multiple inline VS float by dsphoebe (@dsphoebe) on CodePen.

浮动元素高于块级元素:

See the Pen The stacking order: float vs block by dsphoebe (@dsphoebe) on CodePen.

定位元素高于浮动元素。

See the Pen The stacking order: float vs position by dsphoebe (@dsphoebe) on CodePen.

总结为:

从高到低从第一层到第八层:

第一层 正 z-index
第二层 z-index 0 层
第三层 内嵌元素 / 文本
第四层 浮动元素
第五层 块级元素
第六层 border
第七层 background
第八层 负 z-index

如果相同层级的元素,后出现的会盖住先出现的。

堆叠上下文

根据元素自身的属性按照优先级顺序占用堆叠上下文的空间。

堆叠的属性及元素:

  • HTML
  • z-index 值 不为 auto 的 绝对/相对定位
  • z-index 值 不为 autoflex item 元素
  • opacity 不为 1
  • transform 不为 none
  • mix-blend-mode 不为 normal
  • filter 不为 none
  • perspective 不为 none
  • isolation 不为 isolate
  • positionfixed
  • will-change 指定了 CSS 属性,即使没指定这些属性的值
  • -webkit-overflow-scrollingtouch

z-index

多个堆叠上下文间,z-index 父级越大的小子级大于小父级的大子级。

See the Pen The stacking context: z-index by dsphoebe (@dsphoebe) on CodePen.

son2 的 z-index 值大于 son1,但是 son1 却显示在 son2 上面一层,因为 father1 的 z-index 值大于 father2 的 z-index 值。

深入阅读

深入理解CSS中的层叠上下文和层叠顺序