能否在背景图片上使用-webkit-filter: blur();?

34

是否可以在background-image上使用-webkit-filter: blur();

我已经尝试了这段代码,但它只会模糊除background-image以外的所有内容:

body {
  background-image: url('http://www.publicdomainpictures.net/pictures/10000/velka/pebbles-and-sea-11284647414Rbeh.jpg');
  background-attachment: fixed;
  -webkit-filter: blur(5px);
}

我已经搜索了一段时间,但找不到任何资源描述如何做到这一点。

3个回答

48

未来的用户:这不支持IE7、IE8、IE9、IE10、IE11或当前版本的EDGE。

除非你有备用方案,否则不要在真实网站上使用。

如果你正在寻找不依赖于额外标记的解决方案,你可以将背景图像和过滤器应用于body上的伪元素。

body {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
    height: 100%;
}
body:before {
    content: "";
    position: absolute;
    background: url(http://lorempixel.com/420/255);
    background-size: cover;
    z-index: -1; /* Keep the background behind the content */
    height: 20%; width: 20%; /* Using Glen Maddern's trick /via @mente */

    /* don't forget to use the prefixes you need */
    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);
}

Check it out this JsFiddle.


1
如果您不关心IE7或更早版本的支持,则可以使用此方法。 - Rick Calder
11
@RickCalder 真的吗?这是关于Webkit滤镜,连IE11都不支持它。 - Hashem Qolami
1
我认为不需要使用较小的宽度/高度和变换。这在使用全屏GIF时很有用,因为画布必须在每一帧重新绘制,但是如果将单帧图像用作背景,则不应该出现任何主要的CPU问题。如果使用单帧图像可以获得任何收益,那么它们应该是最小的 - 尽管我还没有测试过这一点。 - Bram Vanroy
1
Edge 14现在支持过滤器。 - Okku

21
不要把它应用于身体,将其应用于完整大小的容器中,设置容器的大小和位置为绝对,然后将其余内容设置为相对,并设置z-indexes。
<body>
<div class="bgImageContainer">
</div>
<div class="content"> Some text and stuff here</div>
</body>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
.bgImageContainer{
    background-image:url('http://www.whitegadget.com/attachments/pc-wallpapers/16950d1224057972-landscape-wallpaper-blue-river-scenery-wallpapers.jpg'); 
    width:500px;
    height:400px;
    -webkit-filter: blur(5px);
    z-index:0;
    position:absolute;
}
.content{
    z-index:10;
    position:relative;
}

编辑 - 更新了代码片段,旧图像已经无法使用。

http://jsfiddle.net/Yr2zD/1130/


1
有人尝试过在全屏背景图像中实现这个吗?在Chrome浏览器中会严重降低性能。 - smoizs
有趣的是,一个多年之后这个答案突然遭到了负评和取消赞 lol。新选择的答案很好,但它并没有涵盖 IE 8 版本之前的浏览器。 - Rick Calder
1
这种方法会对Android浏览器产生巨大的性能影响,因为每个对象在背景上的绘制操作都需要更长的时间。 - NicolasZ
1
因为在当前的浏览器中它不能很好地工作,所以对一个2年前的答案进行投反对票...... - Rick Calder
1
不工作在哪里?在Chrome中运行得很好。 fiddle中的图像无法正常工作,但代码仍然可以。使用新图像更新了fiddle。@Dev_Man - Rick Calder
显示剩余3条评论

4
如果需要全屏背景,那么这是我最好的解决方案。
body {
    //background-color: black;  use it if you don't want the background border
}
body:before {
    content: '';
    position: fixed;
    width: 100vw;
    height: 100vh;
    background-image: url('http://www.publicdomainpictures.net/pictures/10000/velka/pebbles-and-sea-11284647414Rbeh.jpg'); // your image
    background-position: center center;
    background-repeat: no-repeat;
    background-position: 100% 100%;
    background-size: cover;
    filter: blur(2px);
    z-index: -9;
}

2
这是一个很好的答案!谢谢。不过为什么会有边框?-- 编辑我已经得到了答案,这都是因为blur()。可以使用transform: scale(1.1);来去掉边框。https://dev59.com/A14b5IYBdhLWcg3wojBg - tomsihap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接