Last Updated: September 09, 2019
·
4.724K
· twopoint718

CSS grayscale

Let's say that you want to do a kind of image "rollover" effect where a logo is grayscale until the mouse rolls over. Then the image is in full-color. It is a great fit for those times when you may want something to be less noticeable and only get "focus" when the user shows interest.

If you do a search for "CSS grayscale" you'll get a bunch of good hints on how to accomplish this. These are mostly right as far as they go:

Here's an example:

/* Firefox 10+, Firefox on Android */
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><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>#grayscale");

 /* IE6-9 */
filter: gray;

/* Chrome 19+, Safari 6+, Safari 6+ iOS */
-webkit-filter: grayscale(100%);

But this very common solution is somewhat wrong. The first thing is that it is using the wrong matrix. The second is that if you did use the correct matrix, it would be redundant, because the correct operation is already defined. Here's the CSS you should use:

/* Firefox 10+, Firefox on Android */
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'saturate\' values=\'0\'/></filter></svg>#grayscale");

 /* IE6-9 */
filter: gray;

/* Chrome 19+, Safari 6+, Safari 6+ iOS */
-webkit-filter: grayscale(100%);

The feColorMatrix is replaced by:

<feColorMatrix type='saturate' values='0'/>

which completely desaturates the image (removes all color) and the reverse is:

<feColorMatrix type='saturate' values='1'/>

Simpler and correct.

1 Response
Add your response

b/w to color transition animation is not working on Firefox.

    -webkit-transition: 1s all ease-in;
-o-transition: 1s all ease-in;
-moz-transition: 1s all ease-in;
transition: 1s all ease-in;
filter: grayscale(0%)!important;
-webkit-filter: grayscale(0%);
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'saturate\' values=\'1\'/></filter></svg>#grayscale");
over 1 year ago ·