How to constantly alternate two images

Viewed 216

I'm trying to use CSS or jQuery to constantly switch between two images. What I have works ok, but it's essentially placing an image on top of the other one, which causes issues if the images I'm using are transparent.

section {
  position: relative;
}

section img {
  position: absolute;
  width: 200px;
}

.top {
  animation-name: fade;
  animation-iteration-count: infinite;
  animation-duration: 1s;
  animation-direction: alternate;
}

@keyframes fade {
  0% {
    opacity: 1;
  }
  25% {
    opacity: 1;
  }
  75% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}
<section>
  <img class="bottom" src="https://placeimg.com/640/480/nature">
  <img class="top" src="https://placeimg.com/640/480/arch">
</section>

Codepen: https://codepen.io/Rhys_Eng/pen/NWdwxaO

1 Answers

To solve the issue with transparent images overlaying each other you can use your current technique to fade out the underlying image as the new one is displayed over it. To do that add a 1 second delay to its animation. Try this:

section img {
  position: absolute;
  width: 200px;
  animation: fade 1s infinite alternate;
}

.bottom {
  animation-delay: 1s;
}

@keyframes fade {
  0% { opacity: 1; }
  25% { opacity: 1; }
  75% { opacity: 0; }
  100% { opacity: 0; }
}
<section>
  <img class="bottom" src="https://placeimg.com/640/480/nature">
  <img class="top" src="https://placeimg.com/640/480/arch">
</section>

If you wanted to change the image without fading, while still using CSS alone, then you can amend the keyframes to this:

@keyframes fade {
  0% { opacity: 1; }
  49% { opacity: 1; }
  50% { opacity: 0; }
  100% { opacity: 0; }
}
Related