1

I have 4 elements with a gradient background I want to animate.

I've created an example:

.element div {
  display: inline-block;
  height: 16px;
  animation: slide 2s infinite;
  animation-timing-function: linear;
  background: linear-gradient(90deg, rgba(242,243,245,1) 0%, rgba(242,243,245,1) 40%, rgba(223,223,223,1) 50%, rgba(242,243,245,1) 60%, rgba(242,243,245,1) 100%);
}

.element div:nth-child(1) {width: 75%;}
.element div:nth-child(2) {width: 65%;}
.element div:nth-child(3) {width: 55%;}
.element div:nth-child(4) {width: 45%;}

@keyframes slide {
  from { background-position: 0 0; }
  to { background-position: 1300px 0; }
}

html,
body {
  height: 100%;
}
<div class="element">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

This is the animation:

@keyframes slide {
  from { background-position: 0 0; }
  to { background-position: 1300px 0; }
}

As you can see this is set to 1300px so the animations for other elements are not correct

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185

1 Answers1

2

You can adjust your code like below:

.element div {
  display: inline-block;
  height: 16px;
  animation: slide 2s infinite;
  animation-timing-function: linear;
  background: 
    linear-gradient(90deg, rgba(242,243,245,1) 0%, rgba(242,243,245,1) 40%, rgba(223,223,223,1) 50%, rgba(242,243,245,1) 60%, rgba(242,243,245,1) 100%);
  background-size:200% 100%; /*added this*/
}

.element div:nth-child(1) {width: 75%;}
.element div:nth-child(2) {width: 65%;}
.element div:nth-child(3) {width: 55%;}
.element div:nth-child(4) {width: 45%;}

@keyframes slide {
  from { background-position: 100% 0; }
  to { background-position: -100% 0; }
}
<div class="element">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

You can check this answer for more details : https://stackoverflow.com/a/51734530/8620333

Temani Afif
  • 245,468
  • 26
  • 309
  • 415