Cheesetoast

Brain Food for Web Developers

applegray

Add Grayscale to Images on Hover Using CSS

Here’s a useful bit of code for converting images to black and white using CSS. This can be useful when you want to add a grayscale-to-colour hover effect to your images.

Add the following CSS class to your image elements:

img.grayscale{ 
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);  /* For Webkit browsers */
    filter: gray;  /* For IE 6 - 9 */
    -webkit-transition: all .6s ease;  /* Transition for Webkit browsers */
}

The hover effect:

img.grayscale:hover{ 
    filter: grayscale(0%);
    -webkit-filter: grayscale(0%);
    filter: none;
}

See the Pen sfCKa by Graham Clark (@Cheesetoast) on CodePen.

The above CSS code currently works for Chrome and IE. Safari won’t work yet, but version 5.2 (coming soon) should support the filter. Until then the code will degrade gracefully.

To get it working on Firefox we need to use the following SVG layer:

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"); /* Firefox 10+, Firefox on Android */

Here is the complete snippet:

img.grayscale{
filter: grayscale(100%);
-webkit-filter: grayscale(100%); /* For Webkit browsers */
filter: gray; /* For IE 6 - 9 */
-webkit-transition: all .6s ease; /* Fade to color for Chrome and Safari */
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"); /* Firefox 10+, Firefox on Android */
}

img.grayscale:hover{
filter: grayscale(0%);
-webkit-filter: grayscale(0%);
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

6 Comments

  1. The filter format is for IE right ?, what version of IE ?.

  2. Is this work on mozilla and opera ?,
    i mean the -moz- and -o- syntax.

    • It works for Firefox (using the SVG layer) but not for Opera. Now that Opera has moved to the webkit / blink engine it has dropped the -o- prefix.

  3. Its not working in ie can you please provide me help please