Udders
Udders

Reputation: 6986

cross fading 2 elements to creat a looping animation with no js

I am wanting to animate an element so it cycles between "0% interest free credit" and "free delivery", I am trying to achieve this with no javascript, but I am only able to get the first element to fade away and not get the second to fade in.

.parent {
  position: relative;
}

.parent p {
  position: absolute;
  top: 0;
  left: 0;
}

.parent p:first-child {
  animation: hide 2s ease-in
}

.parent p:last-child {
  opacity: 0;
  animation: show 2s ease-in animation-delay:2s;
}

@keyframes show {
  to {
    opacity: 1;
  }
}

@keyframes hide {
  to {
    opacity: 0;
  }
}
<div class="parent">
  <p>0% interest free credit</p>
  <p>free delivery</p>
</div>

What am I doing wrong I would like 1 fade out as the other fades in, and for it to loop endlessly.

Upvotes: 2

Views: 122

Answers (1)

Jon Uleis
Jon Uleis

Reputation: 18649

First, you need to make sure your animation is set to loop. Use the keyword infinite as your animation-timing-function for that.

Second, we can restructure your animation to happen in one reusable keyframe sequence that shows and hides the element. By making the whole animation 4 seconds long and offsetting it by half of that (2 seconds) on one element, we achieve a seamless loop of the two elements fading in and out:

.parent {
  position: relative;
}

.parent p {
  animation: show 4s infinite;
  position: absolute;
  top: 0;
  left: 0;
}

.parent p:last-child {
  animation-delay: -2s;
}

@keyframes show {
  0%, 50%, 100% {
    opacity: 0;
  }
  
  10%, 40% {
    opacity: 1;
  }
}
<div class="parent">
  <p>0% interest free credit</p>
  <p>free delivery</p>
</div>

Upvotes: 1

Related Questions