cssbackgroundcss-animationslinear-gradientskeyframe

CSS Background: Linear Gradient - Animation is not functioning as Wished to be


I am facing an issue implementing the animation. The below code snippet is working fine. Currently, the background is animating from left to right only. But I want to reverse the above animation when its cycle ends (reaches the bottom right corner), then the animation should start from there to the left.

I also tried adding a new animation with a 1.5s delay (when the first animation ends) by changing the background position (with javascript), but it didn't work.

I've already read all the possible answers but didn't find a useful one. Can anyone assist with a suggestion/alternative approach or point out what I'm doing wrong? Any help would be greatly appreciated..! 🤗

.user-img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  animation: bg-slide 1.5s ease infinite;
  border: 6px solid rgba(255, 255, 255, 0.12);
  background: 0 0/300% 300% linear-gradient(-60deg, #eee 40%, #18d26e 50%, #eee 60%);
}

@keyframes bg-slide {
  from {
    background-position: 100% 50%;
  }
  to {
    background-position: 0 50%;
  }
}
<img src="https://images.unsplash.com/photo-1630208232589-e42b29428b19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8cHJvZmlsZSUyMHBob3RvfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=400&q=60" alt="user-image" class="user-img" />


Solution

  • You have to add alternate to your animation setting (for the animation-direction):

    .user-img {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      animation: bg-slide 1.5s ease infinite alternate;
      border: 6px solid rgba(255, 255, 255, 0.12);
      background: 0 0/300% 300% linear-gradient(-60deg, #eee 40%, #18d26e 50%, #eee 60%);
    }
    
    @keyframes bg-slide {
      from {
        background-position: 100% 50%;
      }
      to {
        background-position: 0 50%;
      }
    }
    <img src="https://images.unsplash.com/photo-1630208232589-e42b29428b19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8cHJvZmlsZSUyMHBob3RvfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=400&q=60" alt="user-image" class="user-img" />