Image transition to another image on hover

I want the transition of the image to another image to freeze. But after using the following code, the image size is larger than the page, and when you hover over the image, the image disappears and no other image is visible.

HTML

<html>
    <head>
     <title></title>
     </head>
    <body>
      <div id="cssfade">
       <img src="image1.jpg" height:200px;width:300px;/>
       </div>
    </body>
</html>

CSS

#cssfade { 
    background-image: url('image2.jpg');
    height:200px; 
    width: 300px;
}
#cssfade img {
    -webkit-transition: all ease 1s;
    -moz-transition: all ease 1s;
    -o-transition: all ease 1s;
    -ms-transition: all ease 1s;
    transition: all ease 1s;
}
#cssfade img:hover {
    opacity:0;
}
+4
source share
3 answers

I assume the image in the div is content, so I left it there and just moved the hover to take effect when the wrap of the div freezes.

#cssfade {
  width: 300px;
  height: 200px;
  background-image: url(http://lorempixel.com/300/200/sports/2/);
}
#cssfade img {
  width: 300px;
  height: 200px;
  display: block;
  transition: opacity 1s ease;
}
#cssfade:hover img {
  opacity: 0;
}
<div id="cssfade">
  <img src="http://lorempixel.com/300/200/sports/1/" alt="">
</div>
Run codeHide result
+3
source

Use background-imagein div.

In hoverchange background-image.

Transition:

MDN CSS

#cssfade {
  background-image: url('http://lorempixel.com/400/200');
  height: 200px;
  width: 300px;
}
#cssfade:hover {
  -webkit-transition: all ease 1s;
  -moz-transition: all ease 1s;
  -o-transition: all ease 1s;
  -ms-transition: all ease 1s;
  transition: all ease 1s;
  background-image: url('http://lorempixel.com/400/200/sports/1');
}
<div id="cssfade"></div>
Hide result
+2

EDIT. To clarify the difference in Tushar , transitions should be on #cssfade, and not #cssfade:hover, to provide a transition when falling and without freezing.

HTML:

<html>
  <head>
    <title>...</title>
  </head>
  <body>
    <div id="cssfade"></div>
  </body>
</html>

CSS

#cssfade { 
  height:200px; 
  width: 300px;
  background-image: url('image1.jpg') no-repeat;
  -webkit-transition: all ease 1s;
  -moz-transition: all ease 1s;
  -o-transition: all ease 1s;
  -ms-transition: all ease 1s;
  transition: all ease 1s;
}

#cssfade:hover {
  background-image: url('image2.jpg') no-repeat;
}
+2
source

Source: https://habr.com/ru/post/1607418/


All Articles