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

解决<b>元素圆形伪元素被容器背景遮挡的问题

解决元素伪元素被容器背景遮挡的问题

需求:在<b>元素后方生成圆形伪元素(聚光灯效果),使其位于文本与容器背景之间。

现有HTML代码:

<div style="background-color: red;">
    <div style="
        padding: 4% 15%;
        display: flex;
        flex-direction: column;
        height: 100%;
        justify-content: center;
        color: #fff;
    ">
        <h1 style="
            font-weight: 400;
        ">This text should be normal, <b>this</b> this should have a circle behind it.</h1>
    </div>
</div>

现有CSS代码:

b {
    position: relative;
    font-weight: 800;
}
b:before {
    position: absolute;
    content: '';
    background: #8866c5;
    border-radius: 50%;
    width: 130%;
    padding-top: 130%;
    left: -15%;
    transform: translateY(-65%);
    z-index: -1;
}

问题:伪元素会被红色容器的背景遮挡,无法正常显示在文本与背景之间。

修复方案及原理

问题根源在于堆叠上下文:<b>的伪元素设置z-index: -1后,由于<b>的父元素(<h1>)未创建独立的堆叠上下文,伪元素会被归到全局堆叠层级的底部,被普通文档流中的红色容器背景覆盖。

方案一:给父元素创建堆叠上下文

给<h1>添加position: relative和z-index: 0,让它成为独立的堆叠上下文容器,这样伪元素的z-index: -1会相对于<h1>生效,处于<h1>内容的下方、容器背景的上方:

b {
    position: relative;
    font-weight: 800;
}
b:before {
    position: absolute;
    content: '';
    background: #8866c5;
    border-radius: 50%;
    width: 130%;
    padding-top: 130%;
    left: -15%;
    transform: translateY(-65%);
    z-index: -1;
}
/* 新增:为h1创建独立堆叠上下文 */
h1 {
    position: relative;
    z-index: 0;
}

方案二:给<b>元素创建堆叠上下文

直接给<b>设置z-index: 1,让它自身成为堆叠上下文容器,伪元素的z-index: -1会相对于<b>生效,自然处于文本下方、容器背景上方:

b {
    position: relative;
    font-weight: 800;
    z-index: 1; /* 新增:创建堆叠上下文 */
}
b:before {
    position: absolute;
    content: '';
    background: #8866c5;
    border-radius: 50%;
    width: 130%;
    padding-top: 130%;
    left: -15%;
    transform: translateY(-65%);
    z-index: -1;
}

两种方案都能让圆形伪元素正确显示在文本与红色背景之间,实现预期的聚光灯效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 17:56:28