You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么CSS :after伪元素层级低于父元素,hover时父元素背景遮挡它

问题成因
  • 你给.arrow设置的z-index: 1不生效:z-index仅对position值不为static的元素生效,.arrow默认是position: static,既无法让z-index生效,也不能为内部伪元素创建独立的堆叠上下文。
  • 堆叠层级错位:没有独立堆叠上下文时,.arrow的背景和设置了相对定位的::after伪元素处于全局堆叠上下文的同一排序维度,导致hover时父元素背景覆盖了伪元素的SVG内容。
修复方案

只需要两处调整即可:

  1. 给.arrow添加position: relative,触发z-index生效同时创建独立堆叠上下文,内部元素的层级排序会被限制在该上下文内。
  2. 将伪元素的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:15:07