How do I loop a css animation with multiple keyframe definitions?

hitautodestruct picture hitautodestruct · Aug 19, 2014 · Viewed 28.1k times · Source

The Issue

I have two css keyframe animations which I am running on a single element:

.fade-bg {
  animation-name: fade-bg-1, fade-bg-2;
  animation-delay: 0, 6s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

The animations are defined as such:

@keyframes fade-bg-1 {

  from {
      opacity: 0;
      background-image: url(image-1.jpg);
  }

  50% {
      opacity: 1;
      background-image: url(image-1.jpg);
  }

  to {
      opacity: 0;
      background-image: url(image-1.jpg);
  }

}

@keyframes fade-bg-2 { /* Same as fade-bg-1 only with image-2.jpg  */ }

The above works but when it gets to the second animation, it keeps repeating only that animation and does not loop back to fade-bg-1.

I've tried many different combinations of animation-direction but to no avail.

The Question

How do I make it so that the animation returns to fade-bg-1 and repeats itself?

The Example

EXAMPLE

Answer

user3942918 picture user3942918 · Aug 19, 2014

Without javascript I don't think you can. However you can achieve the same effect using a single keyframe animation.

.fade-bg {
  animation-name: fade-bg;
  animation-delay: 0;
  animation-iteration-count: infinite;
  animation-direction: forward;
}


@keyframes fade-bg {
    0% {
        opacity: 0;
        background-image: url('image-1.jpg');
    }

    25% {
        opacity: 1;
        background-image: url('image-1.jpg');
    }

    50% {
        opacity: 0;
        background-image: url('image-1.jpg');
    }

    51% {
        opacity: 0;
        background-image: url('image-2.jpg');
    }

    75% {
        opacity: 1;
        background-image: url('image-2.jpg');
    }

    100% {
        opacity: 0;
        background-image: url('image-2.jpg');
    }
}

EXAMPLE