Wednesday, December 4, 2013

CSS3 to display Image in GrayScale mode

CSS3 really made lot of new innovations in styling the HTML objects.  Here is a trick by which you can convert an image to grayscale with pure CSS.


Create a file "filters.svg"  with below content:



<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>

Use below CSS to refer the above file:

img {
    filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */
}
You can also disable grayscale effect on hover

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

No comments: