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>
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>
<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>
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>
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!