Grayscale image with CSS on Safari 5.x

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:

  • Grayscale.js
  • jQuery GreyScale plugin
  • Hoverizr
  • Do it with canvas (tutorial)

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?


It's really simple, actually:

  • http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html
  • http://jsfiddle.net/KDtAX/487/

I tried using the javascript fallback, but it really made no sense, and it was really slow on large images. This made a lot more sense. Note that there is a new syntax for grayscale, and I had to manually edit the resulting minified CSS from LESS.

Here's my mixin:

.filter (...) {
    -webkit-filter: @arguments;
    -moz-filter: @arguments;
    -ms-filter: @arguments;
    -o-filter: @arguments;
    filter: @arguments;
}

And my class:

.grayscale-hover, .home-image {
    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+, Firefox on Android see http://jsfiddle.net/KDtAX/487/*/
    .filter(grayscale(1) blur(1px));
    filter: gray; /* IE6-9 */
    -webkit-backface-visibility: hidden; /* Fix for transition flickering */
    &:hover {
        .filter(none);
        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");
    }
}

Works and tested in IE 6+, Firefox, Chrome.