在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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章