spratt
spratt

Reputation: 11

How to create fade in/out image animations

I would like to tweak the existing code below, which is working, to support more than just two images.

HTML:

<div id="cf">
  <img class="bottom" src="<?php bloginfo('template_directory') ?>/assets/img/image1" />
  <img class="top" src="<?php bloginfo('template_directory') ?>/assets/img/image2" />
</div>

CSS:

#cf {
  position:relative;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 4s ease-in-out;
  -moz-transition: opacity 4s ease-in-out;
  -o-transition: opacity 4s ease-in-out;
  transition: opacity 4s ease-in-out;
}

@keyframes cf3FadeInOut {
  0% {
    opacity:1;
  }
  45% {
    opacity:1;
  }
  55% {
    opacity:0;
  }
  100% {
    opacity:0;
  }
}

#cf img.top {
  animation-name: cf3FadeInOut;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-duration: 4s;
  animation-direction: alternate;
}

I know it's close, but I'm not sure how to write it so it will support more images. Ideas or suggestions?

Upvotes: 0

Views: 69

Answers (1)

user3589620
user3589620

Reputation:

Set a class, which contains the animation. Use this class for the desired images.

Example

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.fadeOut {
  opacity: 0;
  animation-name: fadeOut;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-duration: 4s;
  animation-direction: alternate;
}
<img class="fadeOut" src="http://via.placeholder.com/40x40">
<img class="fadeOut" src="http://via.placeholder.com/40x40">
<img class="fadeOut" src="http://via.placeholder.com/40x40">

Upvotes: 1

Related Questions