irpas技术客

css实现毛玻璃效果——backdrop-filter_kart jim_css毛玻璃

未知 2670

css实现毛玻璃效果 毛玻璃效果

毛玻璃效果有朦胧美,很适合在以图片为底的文字展示。

用PS比较容易实现毛玻璃效果,网上也有很多教程。但是切图的方法总归有些限制,有局限性,不如直接用代码实现灵活。

在百度里搜索,扑面而来的好多都是使用 filter: blur() + background-attachment 属性 方法实现,个人觉得其实 backdrop-filter 属性更方便,代码量更少,也很好理解。

实际上,MDN上也是使用 backdrop-filter 属性实现的毛玻璃效果。

backdrop-filter CSS 属性可以让你为一个元素后面区域添加图形效果(如模糊或颜色偏移)

参考网址——MDN Web Docs

filter方法

准备——首先给盒子背景图片:

.box{ background: url('./img/bg1.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center center; /* p居中 */ display: flex; align-items: center;justify-content: center; }

之后需要给里面的文字框一个透明背景:

.box p{ padding: 80px 60px; border-radius: 12px; background-color: rgba(255,255,255,.2); }

接着实现毛玻璃效果,由于直接给p加上模糊效果会导致上面的文字也会变模糊不清。

所以需要曲线救国,给p标签的伪元素加模糊,但是又会导致看不见后面的图片背景。

所以又需要给伪元素加上背景图片。

.box p{ padding: 80px 60px; font-size: 24px;border-radius: 12px; background-color: rgba(255,255,255,.2); position: relative; overflow: hidden; } .box p::before{ content: ''; // 伪元素大小与父元素一致 position: absolute; top: 0;bottom: 0;left: 0;right: 0; background-color: rgba(255,255,255,.5); background: url('./img/bg1.jpg'); background-position: center center; background-repeat: no-repeat; background-size: cover; }

之后为了让伪元素位于父元素下方,需要给p标签加上z-index: 1,伪元素加上z-index: -1; 但又会发现伪元素内的图片与后面的图片不一致,有需要给伪元素加上background-attachment: fixed;属性才可。

之后给伪元素加上模糊:

filter: blur(10px); -webkit-filter: blur(10px);

至此,实现模糊效果;你会发现这种方法太复杂,代码量大,考虑的因素多。 所以推荐下面这种方法:

backdrop-filter方法

这种方法是我在浏览MDN官网时发现的,官网上的示例就是backdrop-filte属性实现玻璃效果。-MDN:backdrop-filte

首先,给盒子加个图片,p标签加个透明背景。

.container{ width: 400px;height: 400px; background: url('./img/bg1.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center center; /* p居中 */ display: flex; align-items: center;justify-content: center; } .container p{ padding: 40px 30px; font-size: 24px;border-radius: 12px; background-color: rgba(255,255,255,.2); }

之后给p标签加个backdrop-filter: blur(15px);属性即可实现玻璃模糊效果!

加个投影效果会更好:

.container{ width: 400px;height: 400px; background: url('./img/bg1.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center center; /* p居中 */ display: flex; align-items: center;justify-content: center; } .container p{ padding: 40px 30px; font-size: 24px;border-radius: 12px; background-color: rgba(255,255,255,.2); backdrop-filter: blur(15px); box-shadow: 0 0 10px #333; }


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #css毛玻璃 #css3实现毛玻璃效果