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

元素添加transform后z-index失效,如何确保文字层级高于红圈?

问题原因

当给元素添加transform: translateZ(0px)时,会强制创建新的堆叠上下文。此时.black-box内部的所有子元素(包括<p>)的z-index都只能在这个内部上下文中生效,无法突破到外部层级。而.red-box是绝对定位元素,属于body的堆叠上下文,默认会显示在普通流元素(.black-box)上方,所以即使给<p>设置z-index: 2,也会被.red-box盖住。

解决方案(无需额外嵌套div)

方案一:脱离父元素堆叠上下文

给<p>设置position: absolute,让它脱离.black-box的堆叠上下文,直接归属于body的堆叠上下文,再通过定位调整回居中位置,同时保持z-index高于.red-box即可。

修改后的完整代码:

body {
  width: 100vw;
  height: 100vh;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.black-box {
  width: 200px;
  height: 150px;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translateZ(0px);
  border-radius: 20px;
}

.black-box p {
  font-size: 30px;
  position: absolute;
  z-index: 2;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.red-box {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  transform: translateX(-40px);
  z-index: 1;
  border-radius: 100%;
  opacity: 75%;
}
<div class="black-box">
  <p>hello</p>
</div>
<div class="red-box"></div>

方案二:利用3D变换层级

如果不想用绝对定位,也可以给<p>添加transform: translateZ(1px)并设置position: relative。利用CSS 3D变换的z轴层级,让<p>在3D空间中高于.red-box,无需调整定位:

.black-box p {
  font-size: 30px;
  position: relative;
  transform: translateZ(1px);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:59:55