loader

Grayscale image on hover

George Roubie | 17/10/2016 | css3

A common problem

Many are the times that you need to grayscale an image on hovering it and there are some common ways you can do that.

[end]

The bad Way

You can have one image and on hover, with JavaScript you can change the source of the colored image with the grayscale image.

That way, you use JavaScript for something so simple and on hover you make a request for the second image.


The Ugly Way

You can have two image elements and on hover, with CSS you can hide the colored and show the grayscale.

The above ways are not the best way that you can do it.

The second one, even if it uses CSS, it also makes two requests, one for the colored image and one for the grayscale image on page load.

And the Good Way

The best solution is so simple as to use CSS3 filters. Filters are a powerful tool that can use to achieve visual effects like blur or color shifting on an element’s rendering before the element is displayed.

SCSS Code:

// transition
@mixin transition($value) {
  -webkit-transition: $value;
     -moz-transition: $value;
       -o-transition: $value;
          transition: $value;
}

// Grayscale image on hover
.remove-img-color {
  &.smooth {
    @include transition(all .5s ease-in-out);
  }
  &:hover {
    -webkit-filter: grayscale(100%);
            filter: grayscale(100%);
  }
}
// Remove grayscale on hover
.add-img-color {
  -webkit-filter: grayscale(100%);
          filter: grayscale(100%);
  &.smooth {
    @include transition(all .5s ease-in-out);
  }
  &:hover {
    -webkit-filter: grayscale(0%);
            filter: grayscale(0%);
  }
}

With the above SCSS code, if you add the class remove-img-color to an image element, it becomes grayscale when you hover it.

If you add the class add-img-color to an image element, it will be grayscale and when you hover it will be colored.

Finally, if you add the class smooth it to an image element, it will fade-in-out the filter.

You can see the code running here or in my CodePen.

See the Pen Grayscale image on hover by George Roubie (@georgeroubie) on CodePen.