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

CSS样式问题:如何让h1层级高于header的::before和::after伪元素?

解决CSS伪元素遮挡header内h1文本的问题

你的问题核心在于绝对定位的伪元素会默认堆叠在父元素的普通内容之上,即便给header设置了z-index也无法改变内部堆叠顺序——因为伪元素和h1都处于header创建的堆叠上下文当中。

下面提供两种可行的解决办法:

办法一:给h1设置相对定位和z-index

给h1添加position: relative和正z-index值,让它的堆叠层级超过伪元素:

header h1 {
  position: relative;
  z-index: 1;
}

原理:相对定位的元素会创建独立堆叠上下文,z-index:1会让它层级高于默认z-index为auto的伪元素。

办法二:给伪元素设置负z-index

给两个伪元素添加负z-index,将它们放到header背景与内容之间:

header::after, header::before {
  z-index: -1;
}

原理:负z-index会让伪元素的堆叠层级低于父元素内的普通内容(父元素堆叠上下文里,内容默认层级高于负z-index的子元素)。

修改后的完整CSS代码(以办法一为例)

header {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 99;
  background-image: url("Bild1.svg");
  background-size: 100% 100%;
  text-align: center;
  padding: 1px 20px;
}

header::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("Bild2.svg");
  background-size: 100% 100%;
  opacity: .5;
}

header::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: -10px;
  background-image: url("Bild3.svg");
  background-size: 100% 100%;
  opacity: .5;
}

header h1 {
  position: relative;
  z-index: 1;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:25:21