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

Mary-Kate Olsen
Release: 2024-10-26 08:43:30
Original
957 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!