Home  >  Article  >  Web Front-end  >  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
Patricia ArquetteOriginal
2024-10-26 08:39:02131browse

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>

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>
<code class="html"><img class="grayscale" src="grayscale_image.jpg">
<img class="colored" src="colored_image.jpg"></code>

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>
<code class="xml"><svg ...>
  <defs>
    <filter id="filtersPicture">
      <feColorMatrix type="saturate" values="0" />
    </filter>
  </defs>
  <image filter="url(#filtersPicture)" ... />
</svg></code>

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!

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