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

如何让box-shadow显示在带背景图片的元素上方?

如何让Header的阴影显示在带背景图的Content上方?

我有两个元素:一个的内容区域带有背景图片,另一个则没有。两个元素的header都设置了box-shadow属性。如何让阴影显示在带有背景图片的元素上方?

问题原因

其实这是CSS堆叠上下文的默认规则导致的——DOM里后面出现的元素,默认会堆叠在前面元素的上方。你的.content在.header之后渲染,所以哪怕.header有阴影,也会被带背景图的.content给盖住。

解决方案

只需要给.header加两个属性,提升它的堆叠层级,就能让阴影“跑”到背景图上面:

修改后的CSS代码

.testcontainer { 
  width: 200px; 
  display: inline-block; 
  border: 1px solid gray; 
  height: 120px; 
} 
.header { 
  height: 20px; 
  background-color: cornflowerblue; 
  color: white; 
  -webkit-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.12), 0 1px 5px 0 rgba(0, 0, 0, 0.2); 
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.12), 0 1px 5px 0 rgba(0, 0, 0, 0.2);
  /* 新增这两行代码 */
  position: relative;
  z-index: 1;
} 
.content { 
  height: 100px; 
} 
#hasbgimage { 
  background-image: url("https://via.placeholder.com/200x100"); 
  background-size: cover; 
}

HTML代码(无需改动)

<div class="testcontainer"> 
  <div class="header">test with no image</div> 
  <div class="content"></div> 
</div> 
<div class="testcontainer"> 
  <div class="header">test with image</div> 
  <div class="content" id="hasbgimage"></div> 
</div>

为啥这么做?

  • position: relative:得先让.header变成非静态定位元素,不然z-index是不起作用的。
  • z-index: 1:把.header的堆叠层级设为1,默认元素的层级是0,这样.header就会叠在.content上面,阴影自然就能显示在背景图上方了~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:03:20