How can I create a grayscale image with CSS that re-colors on mouse-over?

Susan Sarandon
Release: 2024-10-27 02:35:02
Original
943 people have browsed it

How can I create a grayscale image with CSS that re-colors on mouse-over?

Image Greyscale with CSS & Re-color on Mouse-Over

You can achieve image greyscale with CSS and re-color on mouse-over using several methods. Here's an overview:

Pure CSS (Using a Single Colored Image)

Use CSS filters to convert the image to grayscale and remove the effect on mouse-over:

<code class="css">img.grayscale {
  filter: grayscale(100%);
}

img.grayscale:hover {
  filter: none;
}</code>
Copy after login

Combination of CSS and JavaScript

Create a grayscale image and a colored image, and toggle their visibility on mouse-in and mouse-out events:

<code class="css">img.grayscale {
  opacity: 1;
}

img.colored {
  opacity: 0;
}</code>
Copy after login
<code class="js">document.querySelector('img').addEventListener('mouseover', () => {
  document.querySelector('img.colored').style.opacity = 1;
  document.querySelector('img.grayscale').style.opacity = 0;
});

document.querySelector('img').addEventListener('mouseout', () => {
  document.querySelector('img.colored').style.opacity = 0;
  document.querySelector('img.grayscale').style.opacity = 1;
});</code>
Copy after login

Using SVG Filters (IE10 Only)

Utilize inline SVG with filters to apply a saturation effect and change it on mouse-over:

<code class="html"><svg>
  <defs>
    <filter id="grayscale">
      <feColorMatrix type="saturate" values="0" />
    </filter>
  </defs>
  <image filter="url(#grayscale)" ... />
</svg></code>
Copy after login

By adjusting the value of saturate, you can control the level of grayscale. This method is supported in IE10 and higher.

The above is the detailed content of How can I create a grayscale image with CSS that re-colors on mouse-over?. 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!