Home  >  Article  >  Web Front-end  >  How to Create a Grayscale Image That Re-Colors on Mouseover Using CSS?

How to Create a Grayscale Image That Re-Colors on Mouseover Using CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 08:43:30957browse

How to Create a Grayscale Image That Re-Colors on Mouseover Using CSS?

CSS Grayscaling with Mouseover Re-Coloration

Query:

Create an image that is initially grayscale, but switches to color when the mouse hovers over it. Implement this using IE and Firefox compatible CSS techniques.

Solutions:

Pure CSS (Using Single Colored Image):

This method utilizes CSS filters to achieve the grayscale effect and removes the filter on hover to reveal the original color:

<code class="css">img.grayscale {
  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 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ &amp; Safari 6+ */
}

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

Inline SVG with CSS Transitions:

This approach embeds an SVG element with an image and applies CSS transitions to fade between grayscale and color on hover:

<code class="css">img.grayscale {
  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");
  filter: gray;
  -webkit-filter: grayscale(100%);
  -webkit-transition: all .6s ease;
  -webkit-backface-visibility: hidden;
}

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

svg {
  background: url(https://image-source.jpg);
}

svg image {
  transition: all .6s ease;
}

svg image:hover {
  opacity: 0;
}</code>

The above is the detailed content of How to Create a Grayscale Image That Re-Colors on Mouseover Using CSS?. 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