为什么CSS :after伪元素层级低于父元素,hover时父元素背景遮挡它
问题成因
- 你给
.arrow设置的z-index: 1不生效:z-index仅对position值不为static的元素生效,.arrow默认是position: static,既无法让z-index生效,也不能为内部伪元素创建独立的堆叠上下文。 - 堆叠层级错位:没有独立堆叠上下文时,
.arrow的背景和设置了相对定位的::after伪元素处于全局堆叠上下文的同一排序维度,导致hover时父元素背景覆盖了伪元素的SVG内容。
修复方案
只需要两处调整即可:
- 给
.arrow添加position: relative,触发z-index生效同时创建独立堆叠上下文,内部元素的层级排序会被限制在该上下文内。 - 将伪元素的
z-index: 2统一放到外层的::after规则中,不需要在hover状态下重复声明,保证伪元素永远高于父元素的背景层级。
修改后完整代码
.arrow { cursor: pointer; user-select: none; display: flex; justify-content: center; align-items: center; margin-left: 1em; transition: background-color .1s ease; position: relative; /* 新增:触发z-index生效,创建堆叠上下文 */ z-index: 1; &:hover { background-color: ${backgroundColors.green3}; &:after { background: url(${arrowPointToRightSvg}); } } &:after { position: relative; display: block; content: ' '; height: 13px; width: 7px; background: url(${arrowPointToRightGreenSvg}); background-size: cover; z-index: 2; /* 新增:固定伪元素层级高于父元素背景 */ } }
如果你原有代码结构中不想调整::after的选择器嵌套逻辑,保留原来的& > .arrow:after写法也可以,只要在规则中加上z-index: 2即可。
内容的提问来源于stack exchange,提问作者Jorah-M
相关产品推荐
相关产品推荐

