CSS設定背景模糊
在做一些頁面的時候,為了讓頁面更好看,我們常常需要設定一些背景圖片,但是,當背景圖片太過花哨的時候,又會影響我們的主體內容,所以我們就需要用到 filter
屬性來設定他的模糊值。
html程式碼如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="cover"> <h1>我是需要突出顯示的內容 </div> </body> </html> 複製程式碼
但是如果直接在背景圖片上使用的話,
.cover{ width:600px; height:300px; position:relative; text-align:center; line-height:300px; color:white; background:transparent url(http://91jean.oss-cn-hangzhou.aliyuncs.com/18-8-31/16567303.jpg) center center no-repeat; filter:blur(5px); background-size:cover; } 複製程式碼
可能會造成下面的這種情況。

我們會發現背景和主體內容都變糊了。
解決辦法:給背景圖片增加一個偽元素,將背景圖片和 filter
屬性設定在偽元素上,具體程式碼如下
.cover{ width:600px; height:300px; position:relative; text-align:center; line-height:300px; color:white; } .cover::before{ content:''; position:absolute; top:0; left:0; width:600px; height:300px; background:transparent url(http://91jean.oss-cn-hangzhou.aliyuncs.com/18-8-31/16567303.jpg) center center no-repeat; filter:blur(5px); z-index:-1; background-size:cover; } 複製程式碼
