乐闻世界logo
搜索文章和话题

CSS 如何对背景图像使用 filter 操作?

4个答案

1
2
3
4

CSS filter 属性可以用于在网页元素上应用图形效果,例如模瑕、亮度、对比度等。它不仅可以应用于普通的元素,也可以应用于背景图像。要对元素的背景图像使用 filter 操作,通常有以下几种方法:

  1. 直接在元素上应用: 可以直接在包含背景图像的元素上使用 filter 属性。这将对元素整体(包括文本内容和背景图像)应用滤镜效果。
css
.background-filter { background-image: url('image.jpg'); filter: blur(5px); /* 应用模糊效果 */ }
  1. 使用伪元素: 如果您只想对背景图像应用 filter 而不影响其他内容,可以使用伪元素来实现。通过将背景图像应用于 ::before::after 伪元素,并在该伪元素上使用 filter,我们可以确保只对背景图像应用滤镜效果。
css
.background-filter::before { content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-image: url('image.jpg'); background-size: cover; filter: blur(5px); /* 应用模糊效果 */ } .background-filter { position: relative; z-index: 1; }
  1. 使用父元素的滤镜: 还可以将滤镜效果应用于包含背景图像的元素的父元素。这种方法会让背景图像和任何子元素都受到滤镜效果的影响。
css
.background-filter-parent { filter: blur(5px); /* 应用模糊效果 */ } .background-filter-child { background-image: url('image.jpg'); }

在这些例子中,我们使用了 blur() 函数作为 filter 的值,这将对选中的元素应用模糊效果。CSS filter 还支持其他函数,例如 brightness(), contrast(), grayscale(), sepia(), hue-rotate(), invert(), opacity()saturate(),可以根据需要组合使用这些函数来达到不同的视觉效果。

2024年6月29日 12:07 回复

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

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

shell
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 */ }
2024年6月29日 12:07 回复

为此,您需要重新构造 HTML。您必须模糊整个元素才能模糊背景。因此,如果您只想模糊背景,则它必须是自己的元素。

2024年6月29日 12:07 回复

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

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

您还可以使用backdrop-filter

有一个受支持的属性,称为,目前 Chrome、Firefox、 Edge、Safari 和 iOS Safaribackdrop-filter支持该属性(有关统计信息,请参阅caniuse.com)。

来自Mozilla 开发文档

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

请参阅caniuse.com了解使用情况统计信息。

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

shell
.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 all major browsers */ 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 child content that should not be blurred */ .u-non-blurred { position: relative; z-index: 1; } <div class="background background-filter"> <h1 class="u-non-blurred">Kermit D. Frog</h1> </div>

2024年6月29日 12:07 回复

你的答案