如何仅用CSS实现图片发光效果(无需额外HTML元素)
可行:用CSS伪元素替代额外图片元素
完全可以不用额外的<img>标签实现相同的发光效果,核心是用CSS伪元素生成发光层,替代原来的重复图片元素,具体实现如下:
完整代码
CSS
body { display: flex; justify-content: center; background-color: black; color: white; padding: 2rem; } .wrapper { position: relative; width: 250px; height: 250px; } .image { width: 100%; border-radius: 10px; position: relative; z-index: 1; /* 让原图在发光层上方 */ } .wrapper::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; border-radius: 10px; background: url('https://ia601706.us.archive.org/8/items/mbid-bbeded36-8d04-4b3b-8b8b-6fa2e4fec570/mbid-bbeded36-8d04-4b3b-8b8b-6fa2e4fec570-27549132408.jpg') center/cover no-repeat; filter: blur(30px) saturate(5); z-index: 0; /* 发光层在原图下方 */ }
HTML
<div class="wrapper"> <img class="image" src="https://ia601706.us.archive.org/8/items/mbid-bbeded36-8d04-4b3b-8b8b-6fa2e4fec570/mbid-bbeded36-8d04-4b3b-8b8b-6fa2e4fec570-27549132408.jpg" /> </div>
实现逻辑
- 给图片容器
.wrapper添加伪元素::before,用它来承载模糊饱和的发光效果 - 伪元素的尺寸、圆角和原图保持一致,通过
background加载同一张图片 - 用
z-index控制层级:伪元素在底层,原图在顶层,这样发光效果就会从原图下方透出来 - 最终只需要一个
<img>标签,完全消除了冗余的HTML元素
内容的提问来源于stack exchange,提问作者Filip Östermark
相关产品推荐
相关产品推荐

