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

添加图片灰度滤镜后父元素伪元素消失,如何恢复红色十字遮罩显示

解决图片添加滤镜后十字遮罩线消失的问题

问题原因

当给<img>元素添加filter属性时,浏览器会为该元素创建一个新的堆叠上下文,导致容器的伪元素(十字线)被<img>覆盖,从而出现其中一条线消失的情况。

解决方案

以下三种方法都能解决这个问题,可根据需求选择:

方法一:给伪元素设置层级

直接为容器的伪元素添加z-index: 1,确保十字线在图片上方显示:

div.former::before,
div.former::after {
    position: absolute;
    content: '';
    width: 100%;
    height: 15px; /* cross thickness */
    background-color: red;
    opacity: 0.8;
    z-index: 1; /* 新增:提升伪元素层级 */
}

方法二:给容器添加空滤镜

为容器也创建堆叠上下文,让伪元素的层级相对于容器,避免被图片的堆叠上下文覆盖:

div.former {
    position: relative;
    width: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: #f00;
    filter: none; /* 新增:让容器创建堆叠上下文 */
}

方法三:将滤镜移到容器上

把图片的灰度滤镜应用到容器上,同时让伪元素不受滤镜影响,这样既保留图片灰度效果,也不会触发图片的堆叠上下文:

div.former {
    position: relative;
    width: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: #f00;
    filter: grayscale(0.9); /* 将滤镜移到容器 */
}

div.former::before,
div.former::after {
    position: absolute;
    content: '';
    width: 100%;
    height: 15px; /* cross thickness */
    background-color: red;
    opacity: 0.8;
    filter: none; /* 让十字线不受灰度滤镜影响 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:35:17