如何在CSS中实现基于图像透明区域的内阴影效果?
给带透明区域的图片添加识别形状的内阴影
要实现仅在图片非透明区域内部显示的内阴影,确实无法直接通过box-shadow: inset(会作用于矩形容器)或filter: drop-shadow()(仅支持外阴影)直接实现,但可以通过视觉叠加+缩放的技巧模拟出等效效果:
实现思路
- 用容器包裹图片,设置
overflow: hidden裁剪超出部分 - 在容器内添加伪元素,载入同一张图片并添加
drop-shadow外阴影 - 将伪元素缩放至略小于原图,让阴影被容器裁剪后,仅在原图的非透明区域边缘内部显示,形成内阴影的视觉效果
代码示例
HTML
<div class="img-container"> <img src="https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg" width="100" /> </div>
CSS
.img-container { display: inline-block; position: relative; overflow: hidden; /* 和图片保持一致的尺寸,避免多余空隙 */ width: 100px; height: 100px; } .img-container img { display: block; position: relative; z-index: 1; /* 确保原图在伪元素上方 */ width: 100%; height: 100%; } .img-container::after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; /* 载入同一张图片作为阴影基底 */ background: url('https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg') no-repeat center / 100% 100%; /* 添加外阴影,参数可根据需求调整 */ filter: drop-shadow(0 0 8px rgba(0, 0, 0, 0.7)); /* 缩放伪元素,让阴影被容器裁剪后仅在原图内部显示 */ transform: scale(0.92); }
效果说明
- 伪元素的
drop-shadow会识别图片的透明区域,只在非透明边缘生成阴影 - 通过
transform: scale()缩小伪元素,结合容器的overflow: hidden,把原本的外阴影"限制"在原图的边缘内部,模拟出内阴影的立体感 - 可以通过调整
drop-shadow的模糊半径、颜色透明度,以及scale的缩放比例,来控制内阴影的深浅和范围
进阶优化(可选)
如果不想重复写图片URL,可以使用CSS变量统一管理:
.img-container { --img-url: url('https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg'); /* 其他样式不变 */ } .img-container::after { background: var(--img-url) no-repeat center / 100% 100%; /* 其他样式不变 */ }
内容的提问来源于stack exchange,提问作者Felix Rech
相关产品推荐
相关产品推荐

