Turning images into grayscale with CSS filter property

With CSS3 filter property, we can actually do a lot of image processing now. One of the cool things to do on images is to change them from color to grayscale with pure CSS. Earlier we were mainly dependent on image processing software like photoshop to do that.

Turning Images black & white with CSS

Turning Images black & white with CSS

The grayscale effect is achieved by the CSS3 grayscale filter. Although not all browsers support it currently, you can use this property with some caution. Just make sure that the users experience do not get adversely affected if it does not work in their browsers. In case, you are looking for absolutely same result in all the browsers, I will rather recommend you to use  jQuery. There are a number of plugins available which can help you to get your task done easily.

Using CSS3, however, can be the easiest method to do that. It takes just a few lines of codes!

Grayscale Filter

You need to use following CSS for changing the saturation of your images to turn it black & white (grayscale).

filter: grayscale(100%);

If you wish to achieve this effect on more than one image, it is better to create a class for that.

.grayscale
{
filter: grayscale(100%);
}

Now, you just need to apply this class to your image in html.

<img src="normal-img.jpg" alt="Changing to grayscale" class="grayscale" />

But wait; no browser currently support this property without vendor prefix. We need to add the vendor prefixes for all the popular browsers.

.grayscale
{
-moz-filter: grayscale(100%);
-webkit-filter:grayscale(100%);
-o-filter:grayscale(100%);
-ms-filter:grayscale(100%);
filter: grayscale(100%);
}

This will make the codes ready for the browsers which support it in future also.

If you are worried about internet explorer, good news is that, IE has been supporting filter right since IE4 days. I would say, at least in this front, IE is pioneer, though the code is a little different!

filter: gray;

And if you wish to add the support for earlier versions of webkit browsers, you will need one more line of code like this:

-webkit-filter: grayscale(1);

So, the complete CSS code turns out to be the following.

.grayscale
{
filter: grayscale(100%);
-moz-filter: grayscale(100%);
-webkit-filter:grayscale(100%);
-webkit-filter: grayscale(1);
-o-filter:grayscale(100%);
-ms-filter:grayscale(100%);
filter: gray;
}

Well, that’s it! If you apply this class to any image, it will render in grayscale. And if you don’t want to turn it completely black & white, you can set the grayscale parameter to any value between 0 and 100.

See it working live on CodePen

Tagged on: ,

8 thoughts on “Turning images into grayscale with CSS filter property

  1. Summer

    i am new blogger, i am daily email reader from blogging ways.. i think the tools help me to build links of my images into grayscale with css filter property.

Leave a Reply