如何将 CSS 过滤器应用于背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20039765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:04:35  来源:igfitidea点击:

How to apply a CSS filter to a background image

cssbackground-imagecss-filters

提问by fox

I have a JPEG file that I'm using as a background image for a search page, and I'm using CSS to set it because I'm working within Backbone.jscontexts:

我有一个 JPEG 文件,用作搜索页面的背景图像,我使用 CSS 来设置它,因为我在Backbone.js上下文中工作:

background-image: url("whatever.jpg");

I want to apply a CSS 3 blur filter onlyto the background, but I'm not sure how to style just that one element. If I try:

我想一个CSS 3模糊滤镜应用为背景,但只是一个元素,我不知道如何风格。如果我尝试:

-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);

just underneath background-imagein my CSS, it styles the whole page, rather than just the background. Is there a way to select just the image and apply the filter to that? Alternatively, is there a way to just turn the blur off for every other element on the page?

background-image在我的 CSS下方,它为整个页面设置样式,而不仅仅是背景。有没有办法只选择图像并对其应用过滤器?或者,有没有办法为页面上的每个其他元素关闭模糊?

回答by Aniket

Check out this pen.

看看这支

You will have to use two different containers, one for the background image and the other for your content.

您将不得不使用两种不同的容器,一种用于背景图像,另一种用于您的内容。

In the example, I have created two containers, .background-imageand .content.

在示例中,我创建了两个容器,.background-image以及.content.

Both of them are placed with position: fixedand left: 0; right: 0;. The difference in displaying them comes from the z-indexvalues which have been set differently for the elements.

它们都用position: fixed和放置left: 0; right: 0;。显示它们的差异来自于z-index为元素设置的不同值。

.background-image {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 1;
  display: block;
  background-image: url('https://i.imgur.com/lL6tQfy.png');
  width: 1200px;
  height: 800px;
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

.content {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 9999;
  margin-left: 20px;
  margin-right: 20px;
}
<div class="background-image"></div>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam erat in ante malesuada, facilisis semper nulla semper. Phasellus sapien neque, faucibus in malesuada quis, lacinia et libero. Sed sed turpis tellus. Etiam ac aliquam tortor, eleifend
    rhoncus metus. Ut turpis massa, sollicitudin sit amet molestie a, posuere sit amet nisl. Mauris tincidunt cursus posuere. Nam commodo libero quis lacus sodales, nec feugiat ante posuere. Donec pulvinar auctor commodo. Donec egestas diam ut mi adipiscing,
    quis lacinia mauris condimentum. Quisque quis odio venenatis, venenatis nisi a, vehicula ipsum. Etiam at nisl eu felis vulputate porta.</p>
  <p>Fusce ut placerat eros. Aliquam consequat in augue sed convallis. Donec orci urna, tincidunt vel dui at, elementum semper dolor. Donec tincidunt risus sed magna dictum, quis luctus metus volutpat. Donec accumsan et nunc vulputate accumsan. Vestibulum
    tempor, erat in mattis fringilla, elit urna ornare nunc, vel pretium elit sem quis orci. Vivamus condimentum dictum tempor. Nam at est ante. Sed lobortis et lorem in sagittis. In suscipit in est et vehicula.</p>
</div>

Apologies for the Lorem IpsumText.

Lorem Ipsum文本道歉。

Update

更新

Thanks to Matthew Wilcoxsonfor a better implementation using .content:beforehttp://codepen.io/akademy/pen/FlkzB

感谢Matthew Wilcoxson使用http://codepen.io/akademy/pen/FlkzB更好地实现.content:before

回答by Necrone

pen

钢笔

Abolishing the need for an extra element, along with making the content fit within the document flow rather than being fixed/absolute like other solutions.

消除对额外元素的需求,同时使内容适合文档流,而不是像其他解决方案那样固定/绝对。

Achieved using

实现使用

.content {
  overflow: auto;
  position: relative;
}

Overflow auto is needed, else the background will be offset by a few pixels at the top.

需要自动溢出,否则背景将在顶部偏移几个像素。

After this you simply need

在此之后,您只需要

.content:before {
  content: "";
  position: fixed;
  left: 0;
  right: 0;
  z-index: -1;

  display: block;
  background-image: url('img-here');
  background-size:cover;
  width: 100%;
  height: 100%;

  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

EDITIf you are interested in removing the white borders at the edges, use a width and height of 110%and a left and top of -5%. This will enlarge your backgrounds a tad - but there should be no solid colour bleeding in from the edges.

编辑如果你有兴趣在边缘去除白色边框,使用的宽度和高度110%以及左侧和顶部-5%。这会稍微放大你的背景 - 但应该没有从边缘渗入的纯色。

Updated Pen here: https://codepen.io/anon/pen/QgyewB- Thanks Chad Fawcett for the suggestion.

在此处更新 Pen:https: //codepen.io/anon/pen/QgyewB- 感谢 Chad Fawcett 的建议。

回答by hitautodestruct

As stated in other answers this can be achieved with:

正如其他答案中所述,这可以通过以下方式实现:

  • A copy of the blurred image as the background.
  • A pseudo element that can be filtered then positioned behind the content.
  • 模糊图像的副本作为背景。
  • 可以过滤然后定位在内容后面的伪元素。

You can also use backdrop-filter

你也可以使用 backdrop-filter

There is a supported property called backdrop-filter, and it is currently supported in Chrome 76, Edge, Safari, and iOS Safari (see caniuse.comfor statistics).

有一个名为 的受支持属性backdrop-filter,目前支持 Chrome 76、Edge、Safari 和 iOS Safari(有关统计信息,请参见caniuse.com)。

From Mozilla devdocs:

来自Mozilla 开发文档

The backdrop-filter property provides for effects like blurring or color shifting the area behind an element, which can then be seen through that element by adjusting the element's transparency/opacity.

背景过滤器属性提供了诸如模糊或颜色偏移元素后面区域的效果,然后可以通过调整元素的透明度/不透明度来通过该元素看到这些效果。

See caniuse.comfor usage statistics.

访问caniuse.com获取使用统计信息。

You would use it like so:

你会像这样使用它:

.background-filter::after {
  -webkit-backdrop-filter: blur(5px); /* Use for Safari 9+, Edge 17+ (not a mistake) and iOS Safari 9.2+ */
  backdrop-filter: blur(5px); /* Supported in Chrome 76 */

  content: "";
  display: block;
  position: absolute;
  width: 100%; height: 100%;
}

.background-filter {
  position: relative;
}

.background {
  background-image: url('https://upload.wikimedia.org/wikipedia/en/6/62/Kermit_the_Frog.jpg');
  width: 200px;
  height: 200px;
}
<div class="background background-filter"></div>

Update (12/06/2019): Chromium will ship with backdrop-filterenabled by default in version 76 which is due out 30/07/2019.

更新(12/06/2019):Chromium 将backdrop-filter30/07/2019 到期的76 版中默认启用。

Update (01/06/2019): The Mozzilla Firefox team has announcedit will start working on implementing this soon.

更新(01/06/2019):Mozzilla Firefox 团队宣布将很快开始实施此功能。

Update (21/05/2019): Chromium just announcedbackdrop-filteris available in chrome canary without enabling "Enable Experimental Web Platform Features" flag. This means backdrop-filteris very close to being implemented on all chrome platforms.

更新(21/05/2019)刚刚宣布的Chromiumbackdrop-filter在 chrome canary 中可用,而无需启用“启用实验性 Web 平台功能”标志。这意味着backdrop-filter非常接近在所有 chrome 平台上实现。

回答by posit labs

You need to re-structure your HTMLin order to do this. You have to blur the whole element in order to blur the background. So if you want to blur only the background, it has to be its own element.

您需要重新构建HTML才能执行此操作。您必须模糊整个元素才能模糊背景。所以如果你只想模糊背景,它必须是它自己的元素。

回答by Sumitava Das

Please check the below code:-

请检查以下代码:-

.backgroundImageCVR{
 position:relative;
 padding:15px;
}
.background-image{
 position:absolute;
 left:0;
 right:0;
 top:0;
 bottom:0;
 background:url('http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg');
 background-size:cover;
 z-index:1;
 -webkit-filter: blur(10px);
  -moz-filter: blur(10px);
  -o-filter: blur(10px);
  -ms-filter: blur(10px);
  filter: blur(10px); 
}
.content{
 position:relative;
 z-index:2;
 color:#fff;
}
<div class="backgroundImageCVR">
    <div class="background-image"></div>
    <div class="content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam erat in ante malesuada, facilisis semper nulla semper. Phasellus sapien neque, faucibus in malesuada quis, lacinia et libero. Sed sed turpis tellus. Etiam ac aliquam tortor, eleifend rhoncus metus. Ut turpis massa, sollicitudin sit amet molestie a, posuere sit amet nisl. Mauris tincidunt cursus posuere. Nam commodo libero quis lacus sodales, nec feugiat ante posuere. Donec pulvinar auctor commodo. Donec egestas diam ut mi adipiscing, quis lacinia mauris condimentum. Quisque quis odio venenatis, venenatis nisi a, vehicula ipsum. Etiam at nisl eu felis vulputate porta.</p>
      <p>Fusce ut placerat eros. Aliquam consequat in augue sed convallis. Donec orci urna, tincidunt vel dui at, elementum semper dolor. Donec tincidunt risus sed magna dictum, quis luctus metus volutpat. Donec accumsan et nunc vulputate accumsan. Vestibulum tempor, erat in mattis fringilla, elit urna ornare nunc, vel pretium elit sem quis orci. Vivamus condimentum dictum tempor. Nam at est ante. Sed lobortis et lorem in sagittis. In suscipit in est et vehicula.</p>
    </div>
</div>

回答by a99

The following is a simple solution for modern browsers in pure CSS with a 'before' pseudo element, like the solution from Matthew Wilcoxson.

以下是带有“before”伪元素的纯 CSS 现代浏览器的简单解决方案,例如 Matthew Wilcoxson 的解决方案。

To avoid the need of accessing the pseudo element for changing the image and other attributes in JavaScript, simply use inheritas the value and access them via the parent element (here body).

为了避免访问伪元素来更改 JavaScript 中的图像和其他属性,只需将其inherit用作值并通过父元素访问它们(此处body)。

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);
}

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */
}

回答by saikat

In the .contenttab in CSS change it to position:absolute. Otherwise, the page rendered won't be scrollable.

.contentCSS的选项卡中将其更改为position:absolute. 否则,呈现的页面将无法滚动。

回答by SharpC

Although all the solutions mentioned are very clever, all seemed to have minor issues or potential knock on effects with other elements on the page when I tried them.

尽管提到的所有解决方案都非常聪明,但当我尝试它们时,所有解决方案似乎都存在小问题或可能对页面上的其他元素产生影响。

In the end to save time I simply went back to my old solution: I used Paint.NETand went to Effects, Gaussian Blur with a radius 5 to 10 pixels and just saved that as the page image. :-)

最后为了节省时间,我只是回到了我的旧解决方案:我使用Paint.NET并转到半径为 5 到 10 像素的效果、高斯模糊,并将其保存为页面图像。:-)

HTML:

HTML:

<body class="mainbody">
</body

CSS:

CSS:

body.mainbody
{
    background: url('../images/myphoto.blurred.png');
    -moz-background-size: cover;
    -webkit-background-size: cover;
    background-size: cover;
    background-position: top center !important;
    background-repeat: no-repeat !important;
    background-attachment: fixed;
}

EDIT:

编辑:

I finally got it working, but the solution is by no means straightforward! See here:

我终于让它工作了,但解决方案绝不简单!看这里:

回答by Max Tusken

Of course, this is not a CSS-solution, but you can use the CDN Proton with filter:

当然,这不是 CSS 解决方案,但您可以使用 CDN Proton filter

body {
    background: url('https://i0.wp.com/IMAGEURL?w=600&filter=blurgaussian&smooth=1');
}

It is from https://developer.wordpress.com/docs/photon/api/#filter

它来自https://developer.wordpress.com/docs/photon/api/#filter

回答by codeWithMe

All you actually need is "filter":

您真正需要的只是“过滤器”:

blur(?WhatEverYouWantInPixels?);"

body {
    color: #fff;
    font-family: Helvetica, Arial, sans-serif;
}

#background {
    background-image: url('https://cdn2.geckoandfly.com/wp-content/uploads/2018/03/ios-11-3840x2160-4k-5k-beach-ocean-13655.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;

    /* START */
    /* START */
    /* START */
    /* START */

    /* You can adjust the blur-radius as you'd like */
    filter: blur(3px);
}
<div id="background"></div>

<p id="randomContent">Lorem Ipsum</p>