0

I'm trying to have an animated linear-gradient work vertically, but for some reason it only works when I use a value in px instead of % for the background-position in the keyframes. A percentage would be way better since the width/height of the element is going to change, therefore the background-position should follow.

If the gradient is oriented 90deg, it works but obviously it renders horizontally instead of vertically.

Here is the code :

div {
  width: 50px;
  height: 150px;
  background: linear-gradient(0deg, yellow, orange, red, violet, purple, blue, yellow);
  animation: color 5s linear infinite;
  margin: 50px auto;
}

@keyframes color {
    0% {
        background-position: 0%;
    }

    100% {
        background-position: 200%; /* doesn't work */
        /*background-position: 0 -150px; -> works fine but not ideal */
    }
}
<div></div>

I tried negative value and other background-position variations, without success.

Here is a pen with the code : https://codepen.io/petruhaand1/pen/jOKMrWB

segFault
  • 3,887
  • 1
  • 19
  • 31
janhoegs03
  • 61
  • 3

1 Answers1

0

Using aspects from this answer to a similar question, got it working somewhat:

div {
  width: 50px;
  height: 150px;
  margin: 50px auto;
  overflow: hidden;
  position: relative;
  z-index: 0;
}

div:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  background: linear-gradient( 0deg, yellow, orange, red, violet, purple, blue, yellow) top/100% 50%;
  bottom: 0;
  animation: color 5s linear infinite;
}

@keyframes color {
  0% {
    background-position: top;
  }
  100% {
    background-position: bottom;
  }
}
<div></div>
segFault
  • 3,887
  • 1
  • 19
  • 31