Cheesetoast » grayscale http://www.cheesetoast.co.uk Brain Food for Web Developers Mon, 07 Jul 2014 23:18:22 +0000 en-US hourly 1 http://wordpress.org/?v=4.2.10 Add Grayscale to Images on Hover Using CSS http://www.cheesetoast.co.uk/add-grayscale-images-hover-css-black-white/ http://www.cheesetoast.co.uk/add-grayscale-images-hover-css-black-white/#comments Thu, 14 Feb 2013 01:00:03 +0000 http://www.cheesetoast.co.uk/?p=1057 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. Continue reading

The post Add Grayscale to Images on Hover Using CSS appeared first on Cheesetoast.

]]>
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");
}

The post Add Grayscale to Images on Hover Using CSS appeared first on Cheesetoast.

]]>
http://www.cheesetoast.co.uk/add-grayscale-images-hover-css-black-white/feed/ 6