Desaturating a color image couldn’t be simpler with CSS. The filter is typically applied as a class, as you will often want several images to have the same visual effect:
img.desaturate {
filter: grayscale(100%);
}
Applying the class to the image is also straightforward:
<img src="lena-söderberg.jpg" alt="Lena Söderberg" class="desaturate">
Add An SVG Filter Effect
The CSS shown to this point works in all modern browsers on desktop and mobile, including Microsoft Edge.
To gain the same effect in Firefox previous to version 35, we need to use an SVG filter, which I’ll create as a separate document named desaturate.svg
. The code for that file will be:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<filter id="greyscale">
<feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0 0 0 1 0" />
</filter>
</svg>
If the SVG code looks slightly daunting – and the matrix math behind it is somewhat complex – don’t worry. This is one piece of code that I’d actually encourage you to copy and paste as a generic “recipe”; I’ll explain matrix transformations in a future article.
With the SVG file saved beside our HTML page and test image, the CSS is extended to become:
img.desaturate {
filter: grayscale(100%);
filter: url(desaturate.svg#greyscale);
}
Add Support for IE
To cover IE 6 – 9, we'll apply Microsoft’s simple but proprietary use of filter
:
img.desaturate{
filter: gray;
filter: grayscale(100%);
filter: url(desaturate.svg#greyscale);
}
If you want to add in support for still older versions of Webkit:
img.desaturate{
-webkit-filter: grayscale(1);
-webkit-filter: grayscale(100%);
filter: gray;
filter: grayscale(100%);
filter: url(desaturate.svg#greyscale);
}
The CSS we've written here allows us to visually convert an image to black and white on the fly in our browser, with no need to save new versions in PhotoShop. Using CSS also makes the image much easier to modify: for example, you’ll see that lowering the percentage used in our declaration from 100% to 50% causes a visual blend of the desaturation effect with the original color image.
A slightly easier approach for older versions of Firefox inlines the SVG into the CSS directly, removing the need for any SVG code in the <body>
:
img.desaturate {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
filter: gray;
filter: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' height='0'><filter id='greyscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0' /></filter></svg>#greyscale");
}
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/DcBIH