理解 CSS 的堆叠上下文和堆叠顺序
堆叠顺序
从下面这些例子里面可以看出来,各属性及元素的堆叠顺序。
background 高于负 z-index :
See the Pen The stacking order: background vs negative z-index by dsphoebe (@dsphoebe) on CodePen.
background 在 border 层下面,就像 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值 不为auto的flexitem 元素opacity不为 1transform不为nonemix-blend-mode 不为normalfilter不为noneperspective不为noneisolation不为isolateposition为fixedwill-change指定了 CSS 属性,即使没指定这些属性的值-webkit-overflow-scrolling为touch
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 值。