Blog

News, Insights & Resources

CSS Tutorial: Black and White Images with Color on Hover

by Kurt Elster / Oct. 24, 2013

What if you wanted to have greyscale images on a site that turn to color when the user hovers or taps?

Rather than load two separate images, we can apply a grayscale effect to a single color image using CSS.

img {
    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 */    
   -webkit-filter: grayscale(100%);
   -moz-filter: grayscale(100%);
   -ms-filter: grayscale(100%);
   filter: grayscale(100%);
   filter: gray; /* IE 6-9 */
}

Then, to disable it on hover...

img:hover {
   -webkit-filter: none;
   -moz-filter: none;
   -ms-filter: none;
   filter: none;
}

It's even cross-browser compatible down to IE6.

Don't miss out...