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

如何实现CSS阴影对后方元素产生透明溶解效果且不影响背景

实现元素向后方投射专属阴影(仅作用于后方元素,不影响背景)

要实现你要的效果,核心是让“阴影”仅与后方元素混合,而非直接显示在页面背景上。可以通过伪元素模拟阴影 + 混合模式的方式实现,且能跟随前方元素动态移动:

完整代码

html {
  height: 500px;
  background: url('https://picsum.photos/id/106/2592/1728');
}

/* 容器用于隔离混合效果,避免阴影影响页面背景 */
.container {
  position: relative;
  isolation: isolate;
}

#back {
  position: absolute;
  top: 100px;
  left: 100px;
  width: 200px;
  height: 200px;
  background-color: #FFBBBB;
}

#front {
  position: absolute;
  top: 200px;
  left: 200px;
  width: 200px;
  height: 200px;
  background-color: #BBFFBB;
}

/* 伪元素模拟阴影,仅作用于后方元素 */
#front::before {
  content: '';
  position: absolute;
  /* 对应原box-shadow的偏移位置 */
  top: -30px;
  left: -30px;
  width: 200px;
  height: 200px;
  /* 自定义阴影样式:模糊+半透明,模拟溶解效果 */
  background: rgba(133, 172, 201, 0.5);
  filter: blur(15px);
  /* 混合模式:让阴影与后方元素融合,产生溶解效果 */
  mix-blend-mode: multiply;
  /* 层级放在前方元素后方、后方元素前方 */
  z-index: -1;
  /* 不干扰页面交互 */
  pointer-events: none;
}
<div class="container">
  <div id="back"></div>
  <div id="front"></div>
</div>

关键原理

  1. isolation: isolate:给容器添加这个属性,确保内部元素的混合效果仅作用于容器内,不会渗透到页面背景。
  2. 伪元素模拟阴影:用::before创建独立阴影层,替代原生box-shadow,精确控制混合范围。
  3. mix-blend-mode: multiply:让阴影层与后方红色方块混合,产生类似“溶解”的深色叠加效果,同时不会在背景上显示阴影。
  4. 动态跟随:伪元素是绿色方块的子元素,会自动跟随绿色方块的位置变化,无需额外JS(通过JS移动绿色方块时,阴影也会同步移动)。

如果需要调整阴影的模糊程度、颜色或偏移量,直接修改伪元素的filter、background和top/left值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:38:15