這篇文章主要介紹了CSS設置背景模糊的實現方法,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
在做一些頁面的時候,為了讓頁面更好看,我們常常需要設置一些背景圖片,但是,當背景圖片太過花哨的時候,又會影響我們的主體內容,所以我們就需要用到 filter 屬性來設置他的模糊值。
html代碼如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!DOCTYPE html>
<html>
<head>
<meta charset=
"utf-8"
>
<meta name=
"viewport"
content=
"width=device-width"
>
<title>JS Bin</title>
</head>
<body>
<div class=
"cover"
>
<h
1
>我是需要突出顯示的內容
</div>
</body>
</html>
|
但是如果直接在背景圖片上使用的話,
|
1
2
3
4
5
6
7
8
9
10
11
|
.cover{
width
:
600px
;
height
:
300px
;
position
:
relative
;
text-align
:
center
;
line-height
:
300px
;
color
:
white
;
background
:
transparent
url
(http://
91
jean.oss-cn-hangzhou.aliyuncs.com/
18
-8
-31
/
16567303
.jpg)
center
center
no-repeat
;
filter:blur(
5px
);
background-
size
:cover;
}
|
可能會造成下面的這種情況。

我們會發現背景和主體內容都變糊了。
解決辦法:給背景圖片增加一個偽元素,將背景圖片和 filter 屬性設置在偽元素上,具體代碼如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
.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://
91
jean.oss-cn-hangzhou.aliyuncs.com/
18
-8
-31
/
16567303
.jpg)
center
center
no-repeat
;
filter:blur(
5px
);
z-index
:
-1
;
background-
size
:cover;
}
|

