Gavin Lorenzo
Gavin Lorenzo

Reputation: 3

How can I make an image fade into color upon hover?

I'm very new to web dev right now, and I'm currently trying to make an image fade into color upon hovering over it. This is what I've got right now:

    html:
         <body>
                <img src=imgmonochrome.jpg id=img1>
            </body>


    css:
        #img1 {
            position: top right;
            height:49%;
            width:49%;
            transition: content 0.5s ease;
        }
        #img1:hover {
            transition: content 0.5s;
            content: url('imgcolor.jpg');
        }

The image will switch, but will not fade in.

I've looked all over for answers on this, but I can't find any that use just HTML and CSS (cause I'm illiterate in javascript/jQuery ((but going to learn very soon for this very reason)))

Help would be appreciated.

Upvotes: 0

Views: 1233

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42304

YES, this is possible... But not in the traditional sense.

In order to accomplish this, you'll need to forgo <img />, and instead make use of two images presented with content: url() in :before and :after pseudo-classes. Set the :before to be your starting image, and :after to be your target image. Then set the opacity of :after to 0 by default, and set the two pseudo-elements to sit on top of one another. Finally, set a :hover rule for both :before and :after which toggles their opacity, and use transition: opacity to control the fade.

This can be seen in the following:

* {
  margin: 0;
}

.image:before {
  content: url("https://via.placeholder.com/150/FF0000/00FFFF");
  transition: opacity 0.5s ease;
  -webkit-transition: opacity 0.5s ease;
}

.image:after {
  position: absolute;
  left: 0;
  opacity: 0;
  content: url("https://via.placeholder.com/150/00FFFF/FF0000");
  transition: opacity 0.5s ease;
  -webkit-transition: opacity 0.5s ease;
}

.image:hover:after {
  opacity: 1;
}

.image:hover:before {
  opacity: 0;
}
<div class="image"></div>

Upvotes: 1

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Remove content from the transition and use img tag to set image

<img src="imgmonochrome.jpg" id="img1">

        #img1 {
            position: top right;
            height:49%;
            width:49%;
            transition: 0.5s ease;
        }
        #img1:hover {
            opacity: 0.3;
            background: url(imgcolor.jpg);
        }

Alternatively,

<img src="imgcolor.jpg" id="img1">
#img1 {
   filter: gray;
   -webkit-filter: grayscale(1);
   -webkit-transition: all .5s ease-in-out;
}
#img1:hover {
   filter: none;
   -webkit-filter: grayscale(0);
}

Upvotes: 0

Related Questions