CSS3 Background Transitions

ronaldroe

Super Moderator
Staff member
Recently, I posted on here asking whether CSS3 transitions supported background-image. The answer, of course, was no.

So, I devised a workaround I wanted to share here using a property it does support: opacity.

The effect works in Chrome, Safari, Opera and Firefox 4+. You can see a demo on this page I'm working on here. Mouse over the header to see it.

For this particular instance, I used a sprite and shifted the position. Essentially, what I did was create a div with the background set to the normal state image. Then, I placed a div inside that with the background set to the mouseover state image and set the height and width to 100%. Then, I set the opacity to 0, and on the hover state to 1. The rest was just CSS3 transitions.

Here's the code:

HTML
<div id="header">
<div id="header_inside">
</div>
</div>

CSS
#header{
background: url("http://www.webdesignforum.com/images/sprite.png");
height:150px;
left:50%;
margin:0 0 10px -250px;
position:relative;
width:500px;
}
#header_inside{
background: url("http://www.webdesignforum.com/images/sprite.png") 0 150px;
height:100%;
opacity:0;
width:100%
}
#header_inside:hover{
opacity:1;
-moz-opacity:1;
-webkit-opacity:1;
-o-opacity:1;
transition-property: opacity;
transition-duration:1s;
-webkit-transition-property: opacity;
-webkit-transition-duration:1s;
-o-transition-property: opacity;
-o-transition-duration:1s;
-moz-transition-property: opacity;
-moz-transition-duration:1s;
}

Since opacity doesn't work in IE8 and below, I used a conditional comment to create a regular old hover effect.
 
Last edited:
Top