Skip to content
On this page

一行代码,让网页变为黑白配色

让网页变为黑白配色,是个常见的诉求。而且往往是突如其来的诉求,是无法预知的。当发生这样的需求时,我们需要迅速完成变更发布。

一行代码

css
div {
  filter: grayscale(1);
}
div {
  filter: grayscale(1);
}

为了使整个网页生效,你可以把它放在 <html> 标签的样式里。直接写到 html 文件内,例如:

html
<style>
  html {
    filter: grayscale(1);
  }
</style>
<style>
  html {
    filter: grayscale(1);
  }
</style>

你也可以用内联样式,只要没用 important CSS 语法,内联样式优先级最高:

html
<html style="filter:grayscale(1)">
  ...
</html>
<html style="filter:grayscale(1)">
  ...
</html>

为了更好的兼容性,你可以补一个带 -webkit- 前缀的样式,放在 filter 后面:

html
<html style="filter:grayscale(1);-webkit-filter:grayscale(1)">
  ...
</html>
<html style="filter:grayscale(1);-webkit-filter:grayscale(1)">
  ...
</html>

原理

我们使用了 CSS 特性 filter,并用了 grayscale 对图片进行灰度转换,允许有一个参数,可以是数字(0 到 1)或百分比,0% 到 100% 之间的值会使灰度线性变化。

如果你不想完全灰掉。可以设置个相对小的数字。

兼容性

我们使用了 CSS 特性 filter,兼容性还不错

如果你想获得更好的兼容性,可以加一个前缀 -webkit- :

css
div {
  filter: grayscale(0.95);
  -webkit-filter: grayscale(0.95);
}
div {
  filter: grayscale(0.95);
  -webkit-filter: grayscale(0.95);
}

filter 样式加到 html 还是 body 上

把 filter 样式加到了 <body> 元素上。通常这没有问题。

但如果你的网页内有「绝对和固定定位」元素,一定要把 filter 样式加到 <html> 上。 原因见: drafts.fxtf.org/filter-effe…

引用:

A value other than none for the filter property results in the creation of a >containing block for absolute and fixed positioned descendants unless the element it > applies to is a document root element in the current browsing context.

翻译:

若 filter 属性的值不是 none,会给「绝对和固定定位的后代」创建一个 containing block

除非 filter 对应的元素是「当前浏览上下文中的文档根元素」(即 <html> )。

因此,兼容性最好的方法是把 filter 样式加到 <html> 上。这样不会影响「绝对和固定定位的后代」。 这里小程序有个坑,如果你的页面代码有「绝对和固定定位的后代」,就不能把 filter 样式 加到 <page> 上,而是要找个元素,这个元素没有「绝对和固定定位的后代」,你可以把 filter 样式加到这个元素上。