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

React项目中::after伪元素z-index不生效,Codepen正常本地失效求助

问题根因

这是堆叠上下文规则导致的:当你为设置了position: relative的父元素.card.active添加z-index: 10时,会为该元素创建独立的堆叠上下文。此时子元素(包括::after伪元素)的z-index仅在父元素的内部堆叠体系中生效,哪怕伪元素设置z-index: -1000,也只能排在父元素内部的最底层,无法突破父元素的层级跑到父元素本身的下方。

Codepen测试生效是因为你测试时没有给父元素设置z-index,父元素没有触发独立堆叠上下文,伪元素的负z-index可以正常相对于全局堆叠上下文排列,显示在父元素下方。

解决方案

方案1:移除父元素的z-index配置(最简单)

如果不需要通过z-index调整多个.card之间的层级排序,直接删掉.card.active的z-index: 10即可,保留position: relative不影响伪元素的定位,此时伪元素的负z-index会正常渲染在父元素下方:

.card {
  width: 300px;
  height: 200px;
  background-color: #fff;
  border-radius: 5px;
  &.active {
    position: relative;
    box-shadow: 10px 10px 60px rgba(0, 0, 0, 0.1);
    /* 删掉z-index:10这一行即可 */
    &::after {
      position: absolute;
      content: "";
      top: 0;
      left: 0;
      width: calc(100% + 5px);
      height: calc(100% + 15px);
      border-radius: 5px;
      background-color: #923929;
      z-index: -1000;
      transform: rotateZ(-2deg);
      transform-origin: top left;
    }
  }
}
.cards {
  padding: 5rem;
  display: flex;
  gap: 20rem;
  background-color: #92392920;
}

方案2:保留父元素z-index的适配方案

如果需要保留.card.active的z-index来和其他卡片做层级排序,可以调整内部元素的层级实现效果:将父元素原本的白色背景转移到::before伪元素,让::before层级高于倾斜的::after,卡片文字默认层级高于::before,即可实现预期效果:

.card {
  width: 300px;
  height: 200px;
  border-radius: 5px;
  &.active {
    position: relative;
    z-index: 10; /* 保留z-index用于多卡片层级排序 */
    background-color: transparent; /* 移除原有的白色背景 */
    box-shadow: 10px 10px 60px rgba(0, 0, 0, 0.1);
    &::before {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: 5px;
      background-color: #fff;
      z-index: 1; /* 层级高于::after */
    }
    &::after {
      position: absolute;
      content: "";
      top: 0;
      left: 0;
      width: calc(100% + 5px);
      height: calc(100% + 15px);
      border-radius: 5px;
      background-color: #923929;
      z-index: 0; /* 层级低于::before */
      transform: rotateZ(-2deg);
      transform-origin: top left;
    }
  }
}
.cards {
  padding: 5rem;
  display: flex;
  gap: 20rem;
  background-color: #92392920;
}

内容的提问来源于stack exchange,提问作者Sowmiya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:48:04