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

如何实现遮罩式CSS滤镜?让上层元素滤镜作用于下层背景图

当然可以实现!你要的效果就是让半透明遮罩下方的背景图区域单独变成黑白,其他区域保持原样,用CSS就能搞定,给你两种靠谱的方案:

方案1:用backdrop-filter(最简单,现代浏览器首选)

backdrop-filter就是专门用来给元素背后的内容添加滤镜的属性,完美匹配你的需求。只需要给那个半透明的遮罩元素加上这个属性,再设置好半透明样式就行。

代码示例:

<div class="container">
  <!-- 半透明遮罩,用来给下方背景图加滤镜 -->
  <div class="mask"></div>
</div>
.container {
  width: 800px;
  height: 500px;
  /* 替换成你的背景图 */
  background: url('你的背景图地址') center/cover no-repeat;
  position: relative;
}

.mask {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 300px;
  height: 200px;
  /* 半透明白色遮罩 */
  background: rgba(255,255,255,0.5);
  /* 给背后的背景图施加黑白滤镜 */
  backdrop-filter: grayscale(1);
  /* 可选:加边框方便确认范围 */
  border: 2px solid #333;
}

这个方案代码极简,直接作用于遮罩背后的背景区域,完全不需要额外冗余元素。

方案2:双背景图叠加(兼容旧浏览器)

如果需要兼容不支持backdrop-filter的旧浏览器(比如IE),可以用两层背景图:底层放彩色原图,上层放黑白滤镜后的图,然后控制黑白区域的显示范围,最后把半透明白色层放在最上层。

代码示例:

<div class="container">
  <!-- 黑白背景层 -->
  <div class="bg-blackwhite"></div>
  <!-- 半透明遮罩层 -->
  <div class="mask"></div>
</div>
.container {
  width: 800px;
  height: 500px;
  position: relative;
  overflow: hidden;
}

/* 底层彩色背景 */
.container::before {
  content: '';
  position: absolute;
  inset: 0;
  background: url('你的背景图地址') center/cover no-repeat;
  z-index: 0;
}

/* 上层黑白背景,仅显示遮罩对应区域 */
.bg-blackwhite {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 300px;
  height: 200px;
  background: url('你的背景图地址') center/cover no-repeat;
  filter: grayscale(1);
  z-index: 1;
}

/* 半透明遮罩层 */
.mask {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 300px;
  height: 200px;
  background: rgba(255,255,255,0.5);
  border: 2px solid #333;
  z-index: 2;
}

这个方案需要加载两次背景图,不过浏览器会自动缓存同一张图,不会额外增加加载负担。

小提示

  • 用backdrop-filter时要注意兼容性:Chrome、Firefox(67+)、Safari都支持,IE完全不支持;
  • 两种方案里的遮罩位置和尺寸都可以灵活调整,比如用transform: translate(-50%, -50%)可以快速实现居中效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:59:46