如何使用CSS实现图片局部模糊效果?
实现图片上方文字区域的背景模糊效果
你遇到的问题是直接给文字容器添加filter: blur()会同时模糊文字本身,要实现仅模糊文字下方的图片区域,可以用以下两种方法:
方法一:使用backdrop-filter(推荐)
这是CSS3新增的属性,专门用于模糊元素背后的内容,不会影响元素自身的内容,代码最简洁:
修改后的HTML(结构不变)
<div class="profile-container"> <img class="profile" src="source.png" /> <div class="profile-name">Dog</div> </div>
对应的CSS
.profile-container { position: relative; display: inline-block; /* 让容器自适应图片宽度 */ } .profile { width: 100%; height: auto; display: block; } .profile-name { position: absolute; bottom: 0; left: 0; width: 100%; padding: 15px 0; color: white; text-align: center; /* 核心:模糊背后的图片 */ backdrop-filter: blur(5px); /* 搭配半透明背景,增强文字可读性 */ background-color: rgba(0, 0, 0, 0.3); }
说明:
backdrop-filter: blur(5px)会让文字容器背后的图片区域模糊,数值越大模糊程度越高rgba(0,0,0,0.3)添加半透明黑色背景,避免模糊后的图片影响文字清晰度- 该属性支持现代主流浏览器(Chrome、Firefox、Safari、Edge)
方法二:使用伪元素(兼容旧浏览器)
如果需要兼容不支持backdrop-filter的旧浏览器,可以通过伪元素加载同一张图片并模糊,放在文字下方:
HTML结构
<div class="profile-container"> <img class="profile" src="source.png" /> <div class="profile-name">Dog</div> </div>
对应的CSS
.profile-container { position: relative; display: inline-block; overflow: hidden; /* 隐藏伪元素溢出的模糊边缘 */ } .profile { width: 100%; height: auto; display: block; } .profile-name { position: absolute; bottom: 0; left: 0; width: 100%; padding: 15px 0; color: white; text-align: center; position: relative; z-index: 2; /* 确保文字在模糊层上方 */ } /* 伪元素承载模糊效果 */ .profile-name::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; /* 加载和原图相同的图片 */ background-image: url('source.png'); background-position: bottom center; /* 对齐原图的底部区域 */ background-size: cover; filter: blur(5px); z-index: -1; /* 把模糊层放在文字下方 */ transform: scale(1.1); /* 放大伪元素,避免模糊边缘出现空白 */ }
说明:
- 伪元素单独加载图片并设置模糊,通过
z-index让文字显示在模糊层上方 transform: scale(1.1)是为了抵消模糊效果带来的边缘空白问题
内容的提问来源于stack exchange,提问作者HeyLameRobin
相关产品推荐
相关产品推荐

