在CSS中创建磨砂玻璃效果的两种方法

在本教程中,我将向您展示如何在CSS中创建磨砂玻璃效果。您已经在UI中看到了这一点,例如MacOS和iOS,甚至是现在的Windows,所以这绝对是一种趋势效应。我们可以使用CSS模拟网站中的磨砂玻璃,在本教程中,我将向您展示两种方法。

方法1

第一种方法具有相当广泛的浏览器支持,但它需要比我们将要看到的第二种方法更多的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;
}

方法2

现在有一种替代方法,它使用较少的样式,但享受略少的浏览器支持。我们从相同的.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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章