css毛玻璃效果

先上代码:

<body>
    <main>
        <blockquote>
            "The only way to get rid of a temptation
            <footer><cite>
                    Oscar Wilde,
                    The Picture of Dorian Gray
                    The studio was filled with the rich odour of roses, and when the light summer wind stirred amidst the trees of the garden, there came through the open door the heavy scent of the lilac, or the more delicate perfume of the pink-flowering thorn.
                </cite>
            </footer>
        </blockquote>
    </main>
</body>
body {
    background: url("bao.jpg") 0 / cover fixed;
}

main {
    position: relative;
    background: rgba(70, 63, 63, 0.3);
    overflow: hidden;
}

main::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    filter: blur(20px);
    margin: -30px;
}

效果:

在这里插入图片描述


解析:

  1. main::before的使用原因:
    由于我们不能直接对元素本身进行模糊处理,就对一个伪元素进行处理,然后将其定位到元素的下层,它的背景将会无缝匹配body 的背景;我们添加一个伪元素,将其绝对定位,并把所有偏移量置为0,这样就可以将它完整地覆盖到main 元素之上;

  2. 要把半透明背景换成跟背层完全匹配的背景,要么把body的背景复制过来,要么把伪元素的背景声明合并过去;

  3. 为什么不对main::before 使用background: inherit 呢?因为伪元素会从main(而不是
    body)那里继承样式,这样它只能得到一个半透明的白色背景。

  4. filter(滤镜) 属性

Filter 描述
blur(px) 给图像设置高斯模糊。"radius"一值设定高斯函数的标准差,或者是屏幕上以多少像素融在一起, 所以值越大越模糊;如果没有设定值,则默认是0;这个参数可设置css长度值,但不接受百分比值。
  1. 模糊效果会削减实色像素所能覆盖的范围,削减的幅度正是模糊半径的长度。为了补偿这种情况,我们需要让伪元素相对其宿主元素的尺寸再向外扩大至少20px(即它的模糊半径)。可以通过-20px 的外边距来达到目的,由于不同浏览器的模糊算法可能存在差异,用一个更大的绝对值(比如-30px)会更保险一些。这个方法可以修复边缘模糊消退的问题。
  2. 我们修正了边缘处的模糊消退情况,但现在又出现了模糊效果超出元素范围的情况(有一圈模糊效果超出了容器,这让它看起来不像毛玻璃,而更像玻璃脏了)。这个问题也很容易修复: 只要对main 元素应用overflow: hidden;,就可以把多余的模糊区域裁切掉了。
参考:《css揭秘》

猜你喜欢

转载自blog.csdn.net/qq_43437571/article/details/106481324