在本教程中,小牛云站长将向大家演示如何在CSS中实现磨砂玻璃效果。相信大家已经在UI中看到了这一点,例如MacOS和iOS,甚至是现在的Windows,所以这绝对是一种趋势效应。我们可以使用CSS模拟网站中的磨砂玻璃,在本教程中,小牛云将向大家展示两种方法。
方法一第一种方法具有相当广泛的浏览器支持,但它相对于第二种方法来说会有更多的CSS。首先创建一个带有类的div .container。将使用它来代表磨砂玻璃窗格。然后,将背景图像应用于body元素。在此背景下,需要:
body { background-attachment: fixed; }这样做是因为body的child会继承这个背景图像,希望将它保持在相同的大小。现在要在.container身上创建一个伪元素,这就是我们模糊的东西。因此,应用以下内容:
.container:before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; }这为我们提供了一个涵盖容器元素的元素。现在是时候添加一些颜色,我们将使用盒子阴影:
.container:before { box-shadow: inset 0 0 2000px rgba(255, 255, 255, .5); }为了给我们一个磨砂效果,我们添加了一个模糊滤镜:
.container:before { box-shadow: inset 0 0 2000px rgba(255, 255, 255, .5); filter: blur(10px); }这给了我们大部分我们想要的东西,但它还没有。我们现在需要(如前所述)为伪元素及其父元素设置继承的背景。
.container { background: inherit; } .container:before { background: inherit; }最终实现代码如下:
html代码:
<div class="container"></div>css代码:
body { background: url(https://images.unsplash.com/photo-1544306094-e2dcf9479da3) no-repeat; /* Keep the inherited background full size. */ background-attachment: fixed; background-size: cover; display: grid; align-items: center; justify-content: center; height: 100vh; } .container { width: 30rem; height: 20rem; box-shadow: 0 0 1rem 0 rgba(0, 0, 0, .2); border-radius: 5px; position: relative; z-index: 1; background: inherit; overflow: hidden; } .container:before { content: ""; position: absolute; background: inherit; z-index: -1; top: 0; left: 0; right: 0; bottom: 0; box-shadow: inset 0 0 2000px rgba(255, 255, 255, .5); filter: blur(10px); margin: -20px; }方法二
现在有一种替代方法,它使用较少的样式,但享受略少的浏览器支持。我们从相同的.container元素开始,并将相同的封面背景图像应用于body元素。然后我们将注意力转向一个名为的CSS属性backdrop-filter。我们首先在我们的.container中添加一些显示样式,包括我们喜欢的任何背景颜色(让我们选择淡白色):
.container { background-color: rgba(255, 255, 255, .15); }然后,我们添加过滤器:
.container { background-color: rgba(255, 255, 255, .15); backdrop-filter: blur(5px); }最终实现代码如下:
html代码:
<div class="container"></div>css代码:
body { background: url(https://images.unsplash.com/photo-1544306094-e2dcf9479da3) no-repeat; background-size: cover; display: grid; align-items: center; justify-content: center; height: 100vh; } .container { width: 30rem; height: 20rem; box-shadow: 0 0 1rem 0 rgba(0, 0, 0, .2); border-radius: 5px; background-color: rgba(255, 255, 255, .15); backdrop-filter: blur(5px); }
未经允许不得转载:小牛资源网 » 在CSS中创建磨砂玻璃效果的两种方法
发表评论