Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Background Image with CSS3 Animations

Why this isn't working? What am I doing wrong?

CSS

@-webkit-keyframes test {   0% {     background-image: url('frame-01.png');   }   20% {     background-image: url('frame-02.png');   }   40% {     background-image: url('frame-03.png');   }   60% {     background-image: url('frame-04.png');   }   80% {     background-image: url('frame-05.png');   }   100% {     background-image: url('frame-06.png');   } }  div {   float: left;   width: 200px;   height: 200px;   -webkit-animation-name: test;   -webkit-animation-duration: 10s;   -webkit-animation-iteration-count: 2;   -webkit-animation-direction: alternate;   -webkit-animation-timing-function: linear; } 

DEMO

http://jsfiddle.net/hAGKv/

Thanks in advance!

like image 376
Charles Thomason Avatar asked Sep 06 '11 10:09

Charles Thomason


People also ask

Can you animate a background image in CSS?

You can use CSS to create trendy animations and visual effects. You don't need to know JavaScript or even HTML and create different kinds of animations and environments on your website. Our team at Slider Revolution has researched CSS animated background examples that can help you create fun websites.

How do I animate an image in CSS?

An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want. To use CSS animation, you must first specify some keyframes for the animation. Keyframes hold what styles the element will have at certain times.


1 Answers

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; } @keyframes changeBg{    0%,100%  {background-image: url("https://i.stack.imgur.com/YdrqG.png");}    25% {background-image: url("https://i.stack.imgur.com/2wKWi.png");}    50% {background-image: url("https://i.stack.imgur.com/HobHO.png");}    75% {background-image: url("https://i.stack.imgur.com/3hiHO.png");} }
<div id='mydiv'></div>

Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

like image 141
Rich Bradshaw Avatar answered Sep 19 '22 01:09

Rich Bradshaw