Home  >  Article  >  Web Front-end  >  How to achieve grayscale image transformation on mouse hover with CSS, ensuring compatibility with IE and Firefox?

How to achieve grayscale image transformation on mouse hover with CSS, ensuring compatibility with IE and Firefox?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:42:32120browse

How to achieve grayscale image transformation on mouse hover with CSS, ensuring compatibility with IE and Firefox?

Greyscale and Recolor an Image on Mouse Hover with CSS

Challenge: Transform a colored icon into greyscale and revert it to color when the mouse hovers over it, ensuring compatibility with both IE and Firefox.

Solutions:

1. Pure CSS (Using One Color Image):

This approach utilizes CSS filters to convert the image to grayscale. The filter property is applied to the img element with class grayscale.

CSS:

<code class="css">img.grayscale {
  filter: url("data:image/svg+xml;utf8,"); /* Firefox 3.5+, IE10 */
  filter: gray;                           /* IE6-9 */
  -webkit-filter: grayscale(100%);      /* Chrome 19+ & Safari 6+ */
}

img.grayscale:hover {
  filter: none;
  -webkit-filter: grayscale(0%);
}</code>

2. CSS and SVG (with Inline SVG):

IE10 supports inline SVG, allowing for a cleaner solution. The SVG image is filtered using an feColorMatrix element, and the grayscale effect is applied by setting the saturate value to 0.

HTML:

<code class="html"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 377" width="400" height="377">
  <defs>
    <filter id="filtersPicture">
      <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />
      <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />
    </filter>
  </defs>
  <image filter="url(#filtersPicture)" x="0" y="0" width="400" height="377" xlink:href="image.jpg" />
</svg></code>

The above is the detailed content of How to achieve grayscale image transformation on mouse hover with CSS, ensuring compatibility with IE and Firefox?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn