Convert Color Image to Grayscale with CSS

Converting a color image to grayscale is possible with CSS3. There is no need to keep separate color and grayscale images which can then be displayed for different uses. This is useful in various instances, depending on the design and functionality of the website.

Fortunately there are CSS filters that makes the processing of converting a color image to grayscale very easy. It even works in Internet Explorer and Microsoft Edge.

CSS Code for Color to Grayscale

The first line is for Internet Explorer 6 to 9, the second lines is for Microsoft Edge and Firefox and the webkit filter is for Google Chrome, Safari and Opera.

Despite the promise of cross-browser functionality there may be some issues, especially with later versions of Internet Explorer, Safari and Opera.

Grayscale to Color on Hover

It may be useful to restore the color to the grayscale version when the user hovers over the image with their cursor. Once again this is quite simple with CSS3.

To reverse the effect, meaning display a color image and convert it only to grayscale when the cursor hovers over it, simply swap the code around. In other words the img:hover will contain the code for filtering to grayscale. It is necessary to nullify the grayscale effect of the image when the cursor is not hovering over the image. This can be done by placing the code to negate the grayscale filter in the img section.

Alternative CSS Code

Another option is to create a gray div overlay and change the opacity. However, this is not a true grayscale effect but nevertheless worth considering.

Now simply place the image within a div as follows:

This code could work just as well for a color filter over the image rather than just a graying out effect.

Leave a Comment