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

Posted

技术标签:

【中文标题】如何将 CSS 过滤器应用于背景图像【英文标题】:How to apply a CSS filter to a background image 【发布时间】:2021-11-11 01:01:52 【问题描述】:

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

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

我想将 CSS 3 模糊滤镜应用到背景,但我不确定如何设置那个元素的样式。如果我尝试:

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

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

【问题讨论】:

只模糊图像的一部分:codepen.io/vsync/pen/gjMEWm 【参考方案1】:

看看这个pen。

您必须使用两个不同的容器,一个用于背景图像,另一个用于您的内容。

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

它们都与position: fixedleft: 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>

Lorem Ipsum 文本道歉。

更新

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

【讨论】:

更好的方法是使用 .content:before 代替额外的“背景图像”标记。我在这里更新了笔:codepen.io/akademy/pen/FlkzB fwiw,只有Webkit实现了这个功能,而且只有vendor前缀,所以ms-、o-、moz-前缀没用。 Firefox 35.0 及更高版本默认支持:caniuse.com/#feat=css-filters 刚刚更新到 FF 35,它可以在没有前缀的情况下工作 @EdwardBlack 我认为这不是问题,但要获得永久模糊,您将不得不求助于图像编辑工具。另一种方法可能是使用 phantomJS/headless webkit 浏览器进行某种图像捕获然后提供它,但这是实现相同结果的乏味方法。【参考方案2】:

pen

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

使用

.content 
  /* this is needed or the background will be offset by a few pixels at the top */
  overflow: auto;
  position: relative;


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

  display: block;
  background-image: url('https://i.imgur.com/lL6tQfy.png');
  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);
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

编辑如果您有兴趣移除边缘的白色边框,请使用110% 的宽度和高度以及-5% 的左侧和顶部。这会稍微扩大你的背景 - 但边缘不应有纯色渗出。感谢 Chad Fawcett 的建议。

.content 
  /* this is needed or the background will be offset by a few pixels at the top */
  overflow: auto;
  position: relative;


.content::before 
  content: "";
  position: fixed;
  top: -5%;
  left: -5%;
  right: -5%;
  z-index: -1;

  display: block;
  background-image: url('https://i.imgur.com/lL6tQfy.png');
  background-size:cover;
  width: 110%;
  height: 110%;

  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

【讨论】:

这个限制是你不能在js中操作伪元素。如果您不需要,那么这是一个很好的解决方案。 如果您不喜欢模糊的白色边框,可以将widthheight 增加到110%,然后将-5% 的偏移量添加到topleft content:before 类的。 它对我有用,但我希望当用户滚动页面时背景图像也能滚动。固定位置正在阻止它。如何摆脱这个问题?【参考方案3】:

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

模糊图像的副本作为背景。 可以过滤然后定位在内容后面的伪元素。

你也可以使用backdrop-filter

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

来自Mozilla devdocs:

background-filter 属性提供模糊或颜色移动元素后面区域等效果,然后可以通过调整元素的透明度/不透明度通过该元素看到。

有关使用情况统计信息,请参阅caniuse.com。

你会这样使用它。 如果您不希望里面的内容模糊,请使用实用程序类.u-non-blurred

.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%;
  top: 0;


.background-filter 
  position: relative;


.background 
  background-image: url('https://upload.wikimedia.org/wikipedia/en/6/62/Kermit_the_Frog.jpg');
  width: 200px;
  height: 200px;


/* Use for content that should not be blurred */
.u-non-blurred 
  position: relative;
  z-index: 1;
<div class="background background-filter"></div>
<div class="background background-filter">
  <h1 class="u-non-blurred">Kermit D. Frog</h1>
</div>

更新 (12/06/2019):Chromium 将在版本 76 中默认启用 backdrop-filter is due out 30/07/2019。

更新(2019 年 1 月 6 日):Mozzilla Firefox 团队 has announced 将很快开始实施。

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

【讨论】:

即使它不能在所有浏览器中运行,你也可以得到我的支持,因为它提供了规范正确的非黑客方式来做到这一点。 AFAIK 这是一个非标准功能,因此没有规范。 注意!在 2018 年,浏览器对此的支持显着下降!在 Edge、Firefox 或 Chrome 中不受支持。 @protoEvangelion 似乎它将在 Edge 16+ 中可用,而且我没有看到任何其他浏览器说他们不会实现这一点。有什么事实可以支持这些说法? @hitautodestruct 根据 caniuse.com IE,Edge 16、Firefox 和 Chrome 目前默认不支持此功能。你说得对,Edge 17+ 支持这一点。感谢您指出了这一点。顺便说一句,很酷的答案,我确实希望浏览器实现这一点:)【参考方案4】:

您需要重新构建 html 才能做到这一点。您必须模糊整个元素才能模糊背景。所以如果你只想模糊背景,它必须是它自己的元素。

【讨论】:

【参考方案5】:

请检查以下代码:-

.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>

【讨论】:

【参考方案6】:

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

为了避免访问伪元素以更改 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 */

【讨论】:

它对我不起作用。你有工作的 jsfiddle 吗?【参考方案7】:

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

【讨论】:

【参考方案8】:

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

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

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

【讨论】:

在测试时有什么巧妙的方法可以让localhost 工作? 大分辨率图像的模糊量太微妙了,如何大幅增加模糊量而不让它看起来像块状?宽度有点帮助,但如果我模糊太多,它看起来太块了【参考方案9】:

尽管提到的所有解决方案都非常聪明,但当我尝试它们时,它们似乎都存在小问题或与页面上其他元素的潜在连锁效应。

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

HTML:

<body class="mainbody">
</body

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;

编辑:

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

filter: blur(1px); doesn't work in firefox, IE, and opera

【讨论】:

你下载了 2 张图片【参考方案10】:

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

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>

【讨论】:

【参考方案11】:

现在使用 CSS GRID 变得更加简单和灵活。您只需将模糊背景 (imgbg) 与文本 (h2) 重叠

<div class="container">
 <div class="imgbg"></div>
 <h2>
  Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facilis enim
  aut rerum mollitia quas voluptas delectus facere magni cum unde?:)
 </h2>
</div>

和css:

.container 
        display: grid;
        width: 30em;
      

.imgbg 
        background: url(bg3.jpg) no-repeat center;
        background-size: cover;
        grid-column: 1/-1;
        grid-row: 1/-1;
        filter: blur(4px);
      


     .container h2 
        text-transform: uppercase;
        grid-column: 1/-1;
        grid-row: 1/-1;
        z-index: 2;
      

【讨论】:

【参考方案12】:

CSS 网格对我来说更容易理解。 :)

html, body 
  width: 100%;
  height: 100%;


.container 
  width: 100%;
  height: 100%;
  
  display: grid;
  grid-template-columns: 1fr 6fr 1fr;
  grid-template-rows: 1fr 6fr 1fr;
  grid-template-areas: 
  '. . .'
  '. content .'
  '. . .'; 
  justify-content: center;
  align-items: center;


.backbround 
  width: 100%;
  height: 100%;
  
  grid-area: 1/1/5/5;
  
  background-image: url(https://i.imgur.com/aUhpEz3.jpg);
  filter: blur(5px);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;


.content 
  height: 200px;
  position: relative;
  
  grid-area: content;
  display: flex;
  
  justify-content: center;
  align-items: center;
  color: white;
<div class="container">
  <div class="backbround"></div>
  <div class="content"><h1>Hello World</h1></div>
</div>

【讨论】:

哈哈...没有适合您的老式东西,直接进入网格....喜欢它。【参考方案13】:

此答案适用于具有动态高度和图像的Material Design 水平卡片布局。

为防止由于卡片的动态高度而导致图像失真,您可以使用带模糊的背景占位符图像来调整高度变化。

 

说明

卡片包含在带有 wrapper 类的&lt;div&gt; 中,这是一个弹性盒。 卡片由两个元素组成,一个图像也是一个 链接和内容。 链接&lt;a&gt;,类link,定位 相对。 链接由两个子元素组成,一个占位符&lt;div&gt; class blur 和一个&lt;img&gt; class pic,即清晰的图像。 两者都定位为绝对并具有width: 100%,但pic类具有更高的堆栈顺序,即z-index: 2,将其置于占位符之上。 模糊占位符的背景图片是通过 HTML 中的内联样式设置的。

 

代码

.wrapper 
  display: flex;
  width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.16);
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.16), 0 1px 1px rgba(0, 0, 0, 0.23);
  background-color: #fff;
  margin: 1rem auto;
  height: auto;


.wrapper:hover 
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);


.link 
  display: block;
  width: 200px;
  height: auto;
  overflow: hidden;
  position: relative;
  border-right: 2px solid #ddd;


.blur 
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 100%;
  height: 100%;
  filter: blur(5px);
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);


.pic 
  width: calc(100% - 20px);
  max-width: 100%;
  height: auto;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;


.pic:hover 
  transition: all 0.2s ease-out;
  transform: scale(1.1);
  text-decoration: none;
  border: none;


.content 
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 100%;
  padding: 20px;
  overflow-x: hidden;


.text 
  margin: 0;
<div class="wrapper">
  <a href="#" class="link">
    <div class="blur" style="background: url('http://www.planwallpaper.com/static/assets/img/header.jpg') 50% 50% / cover;"></div>
    <img src="http://www.planwallpaper.com/static/assets/img/header.jpg"  class="pic" />
  </a>

  <div class="content">
    <p class="text">Agendum dicendo memores du gi ad. Perciperem occasionem ei ac im ac designabam. Ista rom sibi vul apud tam. Notaverim to extendere expendere concilium ab. Aliae cogor tales fas modus parum sap nullo. Voluntate ingressus infirmari ex mentemque ac manifeste
      eo. Ac gnum ei utor sive se. Nec curant contra seriem amisit res gaudet adsunt. </p>
  </div>
</div>

【讨论】:

【参考方案14】:
$fondo: url(/grid/assets/img/backimage.png);    
 padding: 0; margin: 0;  
body  
    ::before
        content:"" ; height: 1008px; width: 100%; display: flex; position: absolute; 
        background-image: $fondo ; background-repeat: no-repeat ; background-position: 
        center; background-size: cover; filter: blur(1.6rem);
    

【讨论】:

为您的答案添加解释会很棒。【参考方案15】:

不使用伪类from

body
    background:#cecece;
    font-family: "Scope One", serif;
    font-size: 12px;
    color:black;
    margin:0 auto;
    height:100%;
    width:100%;
    background-image: 
       linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.81)), 
        url(https://i.imgur.com/2rRMQh7.jpg);
       -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover; 
&lt;body&gt;&lt;/body&gt;

【讨论】:

【参考方案16】:

您可以在要应用过滤器的图像上创建一个 div,并将backdrop-filter 用于其 CSS 类。 查看this link

【讨论】:

欢迎提供解决方案链接,但请确保您的答案是useful without it。最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改并且answers that are little more than a link may be deleted,则仅链接答案可能会失效。【参考方案17】:
<!-- Q:Create the blur on parenttal div without effecting the child div -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    *
        margin: 0; padding: 0; box-sizing: border-box;
        font-size: 30px;
    
    .parent
background-image:url(hobby.jpg) ;
height: 100vh;
width: 100vw;
background-repeat: no-repeat;
background-size: cover;
background-position: center;

display: flex;
justify-content: center;
align-items: center;
    
    .child
   
    height: 90vh;
    width: 90vw;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 0, 0, 0.418);
  justify-content: center;
  align-items: center;
    display: flex;
    
 
    
  .text
    
      height: 300px;
      width: 300px;
      border-radius: 500px;
      background-image: url(50cf380e5c78eb174faa8e6ac2cb654a.jpg);
      background-size: cover;
      background-position: center;
      

  
    
    
</style>
<body>
    <div class="parent">
        <div class="child">
       <div class="text"></div>
        </div>
    </div>
</body>
</html>

【讨论】:

您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。【参考方案18】:

这不是我写的,但我注意到有一个使用 CSS SASS 编译器的部分支持的 backdrop-filter 的 polyfill,所以如果你有一个编译管道,它可以很好地实现(它也使用 TypeScript):

https://codepen.io/mixal_bl4/pen/EwPMWo

【讨论】:

【参考方案19】:

div 
    background: inherit;
    width: 250px;
    height: 350px;
    position: absolute;
    overflow: hidden;  /* Adding overflow hidden */


div:before 
    content: ‘’;
    width: 300px;
    height: 400px;
    background: inherit;
    position: absolute;
    left: -25px;  /* Giving minus -25px left position */
    right: 0;
    top: -25px;   /* Giving minus -25px top position */
    bottom: 0;
    box-shadow: inset 0 0 0 200px rgba(255, 255, 255, 0.3);
    filter: blur(10px);

【讨论】:

【参考方案20】:

成功应用背景图片的步骤

    确保您已使用链接标签正确链接了您的 html 和 css &lt;link rel="stylesheet" ref="yourcssdocument.css"&gt;

    我不知道相对目录和子目录,所以我无法评论它

    对我最有效的方法是在 css 中使用 URL 链接

#yourcssdoc .image 
   background-image: url("paste your link here with the quotations")

【讨论】:

你可能错过了他的问题,伙计。该问题与blur 不起作用有关,而不是与如何显示图像有关。【参考方案21】:

如果你想让内容可滚动,请将内容的位置设置为绝对:

content 
   position: absolute;
   ...

我不知道这是否只适合我,但如果不是,那就是解决办法!

既然背景是固定的,那就意味着你有一个“视差”的效果!所以现在,这个人不仅教你如何制作模糊背景,而且还是视差背景效果!

【讨论】:

不回答问题

以上是关于如何将 CSS 过滤器应用于背景图像的主要内容,如果未能解决你的问题,请参考以下文章

使用 CSS 模糊图像或背景图像的边缘

React.js:应用 CSS 过滤器后下载图像

如何通过 CSS 将阴影过滤器应用于 SVG 特定元素/路径

如何通过 CSS 将阴影过滤器应用于 SVG 特定元素/路径

如何将过滤器应用于照片并将其保存到数据库 php css javascript

CSS过滤器:反转不适用于背景色