< main menu

Make picture desaturate with pure CSS

April 19, 2013 -
desaturate

In the BWS developing process, I had to make the images desaturate and then fade them to color at hover. It is possible to make without javascript, only have to use filter and CSS transitions.

How it is possible? First, we have to style the image for it’s final place, and then the magic happens: we can use a desaturate filter for the images, and for hover, we can make it to fade in with CSS transitions.


#single_blog img {

 display: inline-block;
 float: left;
 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+ */
 filter: gray; /* IE6-9 */
 -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
 -webkit-transition: all 0.5s ease-in-out;
 transition: all 0.5s ease-in-out;
 -moz-transition: all 0.5s ease-in-out;
 -o-transition: all 0.5s ease-in-out;
 -ms-transition: all 0.5s ease-in-out;

}

What have we done here? We used a filter for the #single_blog_image. With the -webkit solution, all of the browsers can use the filtered image, and at the end of the style we have used some transition to have the desaturated effect fade out and the original color fade in. This works in all of the major browsers except in Firefox, because it is not a standard method to have the filters fade.

#single_blog img:hover {
 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");
 -webkit-filter: grayscale(0%);
 filter: alpha(opacity=50);
}

To be honest, I couldn’t find any standard solution to fade the filters, so Chrom, Safari and Opera just simply use it, but not Firefox.

Maybe it is not the best solution, but in this case I dont’t need to use some extra script, so at the moment this is the best solution for Us, and it is possible with pure CSS.

balbu web solutions