Grayscale image with CSS on Safari 5.x

alexg picture alexg · Oct 2, 2012 · Viewed 18.7k times · Source

I am trying to show some images on a page where they should be shown in grayscale, except on mouse hover when they smoothly transition into color. I've made it work nicely on IE, Chrome and Firefox, but it doesn't work on Safari 5.x. The problem is on Safari for Mac and Safari for Windows. Here is the code I have so far:

filter: url('desaturate.svg#greyscale'); 
filter: gray;
-webkit-filter: grayscale(1);

The first line loads an external .svg filter (I don't inline it with a url("data:... rule because I want to avoid a bug in old versions of Firefox).

The second line is for IE and seems to work just as well as filter:progid:DXImageTransform.Microsoft.BasicImage(grayScale=1);.

The last line about webkit is supposed to work on Safari 6 and above, as well as Chrome.

Is there any CSS rule to show the images with grayscale on Safari 5.x? Or, if that is not possible, can someone recommend a javascript solution, preferably one that will handle the animation to and from grayscale? I would like to avoid a server-side hack with grayscale images because that will mess up my HTML and then I'll have to do some nasty browser detection to serve HTML conditionally.

thanks

Edit:

As this has turned out to be a "notable question", please don't keep posting here more answers that only work on Safari 6 and above, or answers that include an .svg file in a data url. At the time when I wrote the OP, it was important for me to support some versions of Safari and Firefox that are today considered very dated, but nevertheless that was my original question.

I am well aware that for modern browsers grayscale filtering is easily accomplished with a few lines of CSS code, but the graphics designer was using Safari 5.x and the client was using Firefox 3.x at the time I did this project. The solution that worked for me was what Giona suggested, i.e. to use Modernizr to test for css-filtering, and if it's not supported to fall back to javascript.

If I was doing the same thing today, I'd be telling both to go update their browsers!

Answer

Giona picture Giona · Oct 2, 2012

As you can see on caniuse.com , CSS3 filters are supported by very few browsers at the moment.

There are many JavaScript/jQuery fallback if you Google "javascript grayscale plugin". Here are some:

But i've no experience with them, so i can't suggest you which one is the best.

I tried jQuery Black And White long time ago, and it gave me a lot of issues with relative/absolute positioned images, so maybe avoid it.


Including this Modernizr build into your pages, you can target browser not supporting filters via Javascript:

if(!Modernizr.css_filters){
    /* javascript fallback here */
}

or CSS:

.no-css_filters .element {
    /* css fallback here */
}

Oh, and don't forget dowebsitesneedtolookexactlythesameineverybrowser?