带滚动容器的inset box-shadow覆盖子图片定位问题及解决
解决带滚动容器的内阴影覆盖图片问题
我有一个包含图片的容器,设置了overflow-y: scroll实现垂直滚动。想要添加inset box-shadow覆盖图片,营造图片置于框架后的视觉效果,但遇到问题:用:after伪元素实现覆盖后,阴影会随图片滚动,导致被容器边框遮挡。
初始实现代码
CSS
.map-container { margin: 10px; position: relative; text-align: center; height: 600px; overflow-y: scroll; } .map-container::after { box-shadow: inset 8px 8px 10px #888888; content: ''; display: block; height: 100%; position: absolute; top: 0; width: 100%; }
HTML
<div class="map-container"> <img id="map" src="https://picsum.photos/seed/picsum/800/800" alt="map" height="800px"> </div>
尝试过的无效方法
- 调整绝对定位与z-index
- 将图片设为容器背景图
- 在容器内单独添加阴影div
- 给图片添加inset box-shadow
- 去除overflow并缩小图片
最终解决方案
新增父级div包裹容器和图片,调整图片的position为relative、z-index为-1,并设置容器margin-right: -20px,既解决了阴影滚动问题,同时修正了滚动条位置。
解决方案代码
HTML
<div id="map_shadow"> <div class="map-container"> <img id="map" src="img/pub_map.png" alt="map" height="800px"> </div> </div>
CSS
.map-container { margin-right: -20px; position: relative; text-align: center; height: 600px; overflow-y: scroll; } #map { position: relative; z-index: -1; } #map_shadow { margin: 20px; padding-right: 0px; box-shadow: inset 8px 8px 10px #888888; }
内容的提问来源于stack exchange,提问作者Sampsky
相关产品推荐
相关产品推荐

