Search code examples
htmlcsshovercss-transitionsmousehover

Change image opacity with transition


I want to change the opacity of the first image (img class:top) from 1 to 0 and change the opacity of the second image (img class:bottom) from 0 to 1 on mouseover.

my HTML

<div class="col classtrans"> <img class="bottom" src="/2.png" /> <img class="top" src="3.png" /> </div>

my css

.classtrans {
position:relative !important;
margin:0 auto;
height:281px;
width:450px;
}

.classtrans img.top {
position:absolute !important;
left:0;
-webkit-transition: opacity 1s ease-out;
-moz-transition: opacity 1s ease-out;
-o-transition: opacity 1s ease-out;
transition: opacity 1s ease-out;
}

.classtrans img.bottom {
position:absolute !important;
left:0;
bottom: auto;
opacity:0;
-webkit-transition: opacity 1s ease-in;
-moz-transition: opacity 1s ease-in;
-o-transition: opacity 1s ease-in;
transition: opacity 1s ease-in;
}

.classtrans img.top:hover {
opacity:0;
}

.classtrans img.bottom:hover {
opacity:1;
}

But it does not work. Hover only works on the first image(top) and does not change the opacity of the second image(bottom). Please help me.


Solution

  • To accomplish this, you may want to have an inner tag that you can hover on, like this:

    <div class="col classtrans"> <div class="classtransinner"> <img class="bottom" src="/2.png" /> <img class="top" src="3.png" /> </div> </div>
    

    And then some CSS code:

    .classtransinner {
    
    display: inline-block;
    
    }
    
    .classtransinner:hover img.bottom {
    
    opacity:1;
        
    }
    
    .classtransinner:hover img.top {
    
    opacity:0;
        
    }
    

    Please tell me if this works, and consider marking this as "Correct" if it helped you! :D