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

为何::before伪元素背景会遮挡父元素内容?如何让内容正常显示?

嘿,这个问题我之前也碰到过,咱们一步步拆解哈~

问题原因

核心问题出在堆叠层级(z-index)的默认规则和选择器的作用范围上:

  1. 你的.auth-form-frame设置了position: relative,它会成为内部绝对定位元素的堆叠上下文。
  2. ::before伪元素是position: absolute,默认情况下,绝对定位元素的堆叠层级会高于普通流中的文本节点(也就是父元素里直接写的Some very long text)——因为普通流元素的z-index是auto,绝对定位元素会自动提升层级。
  3. 你写的> *选择器只会选中父元素的直接子元素,但父元素里的文本是「文本节点」,不是HTML元素,根本没被这个选择器命中,自然得不到z-index: 100的设置,就被伪元素的绿色背景完全盖住了。
解决办法

这里有几个靠谱的方案,你可以根据实际场景选择:

方案1:给伪元素设置负z-index

直接给::before伪元素加z-index: -1,让它跑到父元素内容的下方。因为父元素是position: relative,作为堆叠上下文,负z-index的伪元素会被压在父元素所有内容下面,不会遮挡文本:

.auth-form-frame {
  position: relative;
  width: 50rem;
  height: 25rem;
  color: #000;
  font-size: 10rem;
  &:before {
    content: "";
    background-size: cover;
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    background-color: green;
    z-index: -1; /* 新增这行 */
  }
}

方案2:把文本放到子容器里

把父元素里的文本包裹成一个子元素(比如<span>或<div>),这样> *选择器就能命中它,给它加上z-index: 100,让它显示在伪元素上面:

HTML修改:

<div class="auth-form-frame">
  <span>Some very long text</span>
</div>

CSS保持原有代码(可选加position: relative更稳妥):

.auth-form-frame {
  position: relative;
  width: 50rem;
  height: 25rem;
  color: #000;
  font-size: 10rem;
  &:before {
    content: "";
    background-size: cover;
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    background-color: green;
  }
  > * {
    z-index: 100;
    position: relative; /* z-index对static定位元素无效,加这个更稳妥 */
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:57:46