Muhammad Afzal
Muhammad Afzal

Reputation: 1

Change Image on mouse hover and mouse out in CSS

I use below mention code to produce a CSS transition effect. A div shows first image (i.e. 1.jpg), and upon mouse-hover the second image (2.jpg) is appear through CSS transition and when mouse-out the first image is back to display.

I need a third image on mouse-out so kindly help me how i do this through CSS.
My coding is as under:

.mainimg
{
    background-image:url(1.jpg);
    height: 300px;
    width: 300px;
    transition: 1s;
}
.img2
{
    background-image:url(2.jpg);
    background-size:500px 500px;
    width:0px;
    height:300px;
    transition:1s
}
.mainimg:hover .img2
{
    width:300px;
    transition:1s;
}   
<div class="mainimg">

<div class="img2"></div>
 </div>

Upvotes: 0

Views: 1843

Answers (3)

Max
Max

Reputation: 138

what @Franz Thüs says is correct you have to use Javascript for the 3e image. also what @Med7at is saying try using one div and change the image via the :hover

this should work for you.

I used an id instead of an class so only one item will change with those images.

i used colors so you can see the differents.

var mouseOut = document.getElementById("mainimg");

mouseOut.onmouseout = function() {
  this.style.backgroundColor = "orange"; //this.style.background = "url(3.jpg)"
}
#mainimg{
  background:blue; /*background-image:url(1.jpg);*/
  height: 300px;
  width: 300px;
  transition: 1s;
}

#mainimg:hover{
  background:red; /*background-image:url(2.jpg);*/
  background-size:500px 500px; /* this will make the 3 img look missplaced for 1 second.
}
<div id="mainimg"></div>

see the comments what you should put in that line to make it work with the images.

Upvotes: 0

medhatdawoud
medhatdawoud

Reputation: 1188

Try this out: use the same div for containing image

<div class="mainimg">

and use css hover to change image background

.mainimg {
  background-image:url(1.jpg);
  height: 300px;
  width: 300px;
  transition: 1s;
}
.mainimg:hover {
  background-image:url(2.jpg);
  transition: 1s;
}

Upvotes: 2

Franz
Franz

Reputation: 419

The rollover is state is binary in CSS, an element is either being hovered over or it is not. You will need to use JavaScript for doing what you want.

Upvotes: 0

Related Questions