Simple background image transition

A simple way to simulate background image transitioning on hover with css opacity.

by bradleygriffith

HTML

<div id="imageContainer">
<a href="http://stackoverflow.com">
<!-- this is the initial image -->
<img src="http://i.imgur.com/aTROO.gif"></img>
<!-- Thi is the hover image -->
<img src="http://i.imgur.com/j7U3K.gif"></img>
</a>
</div>

CSS

#imageContainer{
   /* The height and width are the size of the images -- which should match */
   width: 103px;
   height: 128px; 
   /* The margins are just for the example and do not matter */
   margin-left: 25px; 
   margin-top: 25px;    
}

#imageContainer img{
   -webkit-transition:opacity 1s;  
   -moz-transition:opacity 1s;  
   -o-transition:opacity 1s;  
   transition:opacity 1s;
   padding: 0px;
   margin: 0px;
}

#imageContainer img:nth-child(1){
    opacity: 1;
}

#imageContainer img:nth-child(2){
    position: relative;
    /* The following 'top' setting is sort of hacky... 
    it's the negative of the height of the images plus a little
    more... this could be improved upon but works*/
    top: -132px;
    left: 0;
    opacity: 0;
}

#imageContainer:hover img:nth-child(1){
    opacity: 0;
}

#imageContainer:hover img:nth-child(2){
    opacity: 1;
}