Search code examples
csscss-animationscss-transforms

How can I connect a CSS animation's end to the beginning so it smoothly continues?


I have a rainbow bar that sits at the top of my page:

.rainbow-bar {    /* Epic rainbow bar */
    height:8px;
    background: black; /* fallback */
    background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
    background-size: 200% 200%;
    animation: moveright 3s ease infinite;
    animation-direction: alternate;
}

So I want the bar to loop forever, moving to the right. I'm bad at explaining so heres an image

This is the current animation code I have which of course just makes it move offscreen then come back, which is exactly what I do not want. If anyone could point me in the right direction I would really appreciate it, thanks.

@keyframes moveright {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}

Solution

  • So it's kinda tricky to do this with just CSS, however this can be achieved by changing the background gradient on the frames. Codepen link

    HTML:

    <div class='bg'>
      <div class='rainbow-bar'>
      </div>
    </div>
    

    CSS:

    .bg {
        background: black; /* fallback */
    }
    
    .rainbow-bar {    /* Epic rainbow bar */
        height: 3px;
        animation: move .75s ease infinite;
    }
    
    @keyframes move {
      0% {
        background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
      }
      14.3% {
        background: linear-gradient(to right, violet, red, orange, yellow, green, blue, indigo);
      }
      28.6% {
        background: linear-gradient(to right, indigo, violet, red, orange, yellow, green, blue);
      }
      42.9% {
        background: linear-gradient(to right, blue, indigo, violet, red, orange, yellow, green);
      }
      57.2% {
        background: linear-gradient(to right, green, blue, indigo, violet, red, orange, yellow);
      }
      71.5% {
        background: linear-gradient(to right, yellow, green, blue, indigo, violet, red, orange);
      }
      85.8% { 
        background: linear-gradient(to right, orange, yellow, green, blue, indigo, violet, red);
      }
      100% {
        background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
      }
    }