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

CSS:含两张背景图的元素,如何仅为其中一张添加阴影?

解决方案:单独给第一张背景图添加阴影

直接给.card元素添加filter: drop-shadow会作用于整个元素(包括两张背景图),没法单独针对第一张背景图生效。要实现这个需求,核心思路是把两张背景图拆分到不同的元素载体中,比如用伪元素承载第一张背景图,这样就能独立给伪元素设置阴影效果。

方法一:使用CSS attr()(现代浏览器支持)

通过伪元素::before承载第一张背景图,利用attr(data-img url)直接读取元素的data-img属性作为背景图,然后给伪元素单独添加阴影:

<div class="card" data-img="https://placehold.co/130x130"></div>
.card {
  border: 1px solid black;
  height: 250px;
  width: 200px;
  position: relative; /* 让伪元素相对当前元素定位 */
  /* 仅保留第二张固定背景图 */
  background: url(https://placehold.co/50x50) no-repeat center bottom 20px;
}

.card::before {
  content: '';
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%); /* 水平居中 */
  width: 130px; /* 和第一张背景图尺寸匹配 */
  height: 130px;
  background: url('') no-repeat center;
  background-image: attr(data-img url); /* 读取data-img作为背景图 */
  filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.3)); /* 单独添加阴影 */
}

这种方式不需要额外的JavaScript代码,伪元素会自动读取data-img属性值。注意:attr(data-img url)仅在现代浏览器中支持。

方法二:使用CSS变量(兼容性更好)

如果需要兼容旧版浏览器,可以用CSS变量传递背景图地址,再通过伪元素读取:

<div class="card" data-img="https://placehold.co/130x130"></div>
.card {
  border: 1px solid black;
  height: 250px;
  width: 200px;
  position: relative;
  background: url(https://placehold.co/50x50) no-repeat center bottom 20px;
  --card-top-img: url(''); /* 定义CSS变量存储第一张图地址 */
}

.card::before {
  content: '';
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 130px;
  height: 130px;
  background: var(--card-top-img) no-repeat center;
  filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.3));
}
document.querySelectorAll(".card").forEach(card => {
  // 将data-img的值赋值给CSS变量
  const topImgUrl = card.dataset.img;
  card.style.setProperty('--card-top-img', `url(${topImgUrl})`);
});

原理说明

通过伪元素将第一张背景图从原元素的多背景中分离出来,伪元素作为独立的“子元素”,可以单独设置filter: drop-shadow,而原元素的第二张背景图不受影响,完美实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:31:25