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; }

可能会造成下面的这种情况。

css里面怎么设置背景透明度(CSS设置背景模糊)(1)

我们会发现背景和主体内容都变糊了。

解决办法:给背景图片增加一个伪元素,将背景图片和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; }

复制代码

css里面怎么设置背景透明度(CSS设置背景模糊)(2)

,