Fading an image into another is pretty easy with CSS. Give the element a background-image, then on it’s :hover, change the background-image. It’s best practice to combine both images into one and shift the background-position rather than use two separate images, that’s the idea of CSS sprites.


.sprite-img {
background: url(../images/sprites.png) no-repeat;
background-position: 0 0;
width: 100px;
height: 100px;
}

.sprite-img:hover {
background: url(../images/sprites.png) no-repeat;
background-position: -100px 0;
}

But changing the background position will result in a scroll effect. What if you need a fade in-out effect?

The best solution to this scenario is to use css animation property.

.sprite-img:hover {
animation: fadein .35s, bp-change 0.01s;
-moz-animation: fadein .35s, bp-change 0.01s; /* Firefox */
-webkit-animation: fadein .35s, bp-change 0.01s; /* Safari and Chrome */
-o-animation: fadein .35s, bp-change 0.01s;
background-position: -100px 0;
}

@-webkit-keyframes fadein { /* Safari and Chrome */
from {
opacity:0;
}
to {
opacity:1;
}
}
<code>@-webkit-keyframes bp-change { /* Safari and Chrome */
from {
background-position:0 0;
}
to {
background-position:-210px 0;
}
}

The above animation performs a fade-in and background-position change. Since the timing-function value(0.01s) is very less, it appears as if the image fades in. Hope it helps!

Advertisements