Home > Web Front-end > CSS Tutorial > How to Achieve Grayscale with Color Restoration on Mouse-Over Using CSS?

How to Achieve Grayscale with Color Restoration on Mouse-Over Using CSS?

Patricia Arquette
Release: 2024-10-26 08:39:02
Original
204 people have browsed it

How to Achieve Grayscale with Color Restoration on Mouse-Over Using CSS?

Greyscaling with Color Restoration on Mouse-over Using CSS

Achieving a grayscale appearance with color restoration on mouse-over is possible through various methods, providing cross-browser compatibility in both IE and Firefox.

Method 1: Pure CSS (Using a Single Colored Image)

This technique utilizes the filter property with vendor prefixes to grayscale the image in all supported browsers:

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

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

Method 2: Pure CSS (Using Two Images)

Another approach involves using two images: a grayscale version and a colored version. The grayscale image is initially displayed, and the hover state transitions to the colored image:

<code class="css">img {
  transition: all .6s ease;
}

img:hover {
  opacity: 0;
}

.grayscale {
  opacity: 1;
}</code>
Copy after login
<code class="html"><img class="grayscale" src="grayscale_image.jpg">
<img class="colored" src="colored_image.jpg"></code>
Copy after login

Method 3: SVG with CSS Filters

For IE10 and modern browsers, inline SVG can be used to apply filters, allowing the grayscale effect to be controlled dynamically:

<code class="css">svg image {
  transition: all .6s ease;
}

svg image:hover {
  opacity: 0;
}</code>
Copy after login
<code class="xml"><svg ...>
  <defs>
    <filter id="filtersPicture">
      <feColorMatrix type="saturate" values="0" />
    </filter>
  </defs>
  <image filter="url(#filtersPicture)" ... />
</svg></code>
Copy after login

The above is the detailed content of How to Achieve Grayscale with Color Restoration on Mouse-Over 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