0

Following code produces sliding gradient animation without any line of javascript code:

html {
  height: 100%
}

body {
  height: 100%;
  margin: 0
}

@keyframes loading {
  from {
    background-position: -5000% 0, 0 0
  }
  to {
    background-position: 5000% 0, 0 0
  }
}

.skeleton {
  height: 100%;
  animation-name: loading;
  animation-duration: 1.5s;
  animation-iteration-count: infinite;
  background-color: #fff;
  background-repeat: no-repeat;
  background-image: linear-gradient(90deg, hsla(0, 0%, 100%, 0), hsla(0, 0%, 100%, .8) 50%, hsla(0, 0%, 100%, 0)), linear-gradient(#e5e5e5 100%, transparent 0);
  background-size: 99% 100%;
}
<div class="skeleton"></div>

I experimented with some properties and still do not understand how it works. Especially, when background-size: 99% 100%; is changed to background-size: 100% 100%; animation slides in opposite direction!

Could you explain it?

j08691
  • 204,283
  • 31
  • 260
  • 272
Paul
  • 25,812
  • 38
  • 124
  • 247

1 Answers1

0

I don't know what's your browser and its version. But on my computer, if background-size: 100% 100% then the animation will be stop. (Actually, the background-position will be ignored)

The idea of this trick is moving background-image (linear-gradient) by background-position. (Check the comment in code below for detail)

About your second question, you should refer this answer CSS background-position ignored when using background-size. A quick summary, you can't use percent for background-position if background-size reaches to 100%. This happens because the image in background has no space to move.

If you insist to use background-size with 100%. I afraid you have to use absolute values.

BTW, I've upgraded the code. Now it looks better.

html {
  height: 100%
}

body {
  height: 100%;
  margin: 0
}

@keyframes loading {/* original code */
  from {/* This is the position of image of the first frame */
    background-position: -5000% 0, 0 0
  }
  to {/* This is the pos of img of the last frame */
    background-position: 5000% 0, 0 0
  }
}

@keyframes betterLoading {
  0% {/* This is the position of image of the first frame */
    background-position: -5000% 0, 0 0
  }
  50% {
    /* This is the pos of img of a frame in the middle happening animation */
    /* If duration is 1s then the pos below will be at 0.5s */
    background-position: 5000% 0, 0 0
  }
  100% {/* This is the pos of img of the last frame */
    background-position: -5000% 0, 0 0
  }
}

.skeleton {
  height: 100%;
  animation-name: betterLoading;
  animation-duration: 1.5s;
  animation-iteration-count: infinite;
  background-color: #fff;
  background-repeat: no-repeat;
  background-image: linear-gradient(90deg, hsla(0, 0%, 100%, 0), hsla(0, 0%, 100%, .8) 50%, hsla(0, 0%, 100%, 0)), linear-gradient(green 100%, transparent 0);
  background-size: 99% 100%, cover;
}
<div class="skeleton"></div>