z-index无效有多种原因。z-index默认值是0,都是0的时候,按照dom元素渲染顺序决定优先级。
1.和position同时使用
z-index搭配position非static的值才生效,如relative、absolute、fixed、sticky。这是最常见的
2.Dom元素层级的问题
如果一个子节点有高优先级(zindex999),而其父节点优先级(zindex1)比要遮盖住的兄弟节点(zindex2)要低,则子节点不生效。也就是说,zindex最好是比对同层级的节点的优先级,想遮盖住父节点外的节点,则要同时管理父节点的zindex。
所以对于优先级高的组件如dialog、toaster一般在最外层添加节点。
<div class="a1" style="width: 300px;height: 300px;">a1 red<div class="b1">b1 blue</div></div><div class="a3">a3 yellow</div><style type="text/css">.a1, .a3 {width: 100px;height: 100px;}.a1 {background-color: red;position: relative;z-index: 1;}.a3 {background-color: yellow;position: relative;top: -400px;z-index: 2;}.b1 {width: 100px;height: 100px;background-color: blue;position: relative;z-index: 999;}</style>
