Search code examples
cssbackground-imagecss-animationslinear-gradients

CSS background gradient transition not working


I'm trying to animate a gradient background with @keyframes but for whatever reason, the animation doesn't take place. I have all vendor prefixes, and I spelled the animation name correctly. I'm using a generator for this: https://www.gradient-animator.com/ which there it works.

See example below:

@-webkit-keyframes warpedBackground {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-moz-keyframes warpedBackground {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@keyframes warpedBackground { 
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}

#gradientsquare {
  width: 300px;
  height: 300px;
  background: linear-gradient(170deg, #003a5d, #94c7e6);
  background-size: 100% 100%;
  
  -webkit-animation: warpedBackground 1s ease infinite;
  -moz-animation: warpedBackground 1s ease infinite;
  animation: warpedBackground 1s ease infinite;
}
<div id="gradientsquare"></div>

The code is pretty much the same, so I'm not sure why mine doesn't work...


Solution

  • By specifying backgrouns-size:100% 100% you made the size of your gradient the same as the div; thus all the values of background-position are equivalent so you won't see any movement. Change the background-size and the gradient will move.

    Make it bigger than the div

    @keyframes warpedBackground { 
        0%{background-position:0% 50%}
        50%{background-position:100% 50%}
        100%{background-position:0% 50%}
    }
    
    #gradientsquare {
      border:1px solid;
      width: 300px;
      height: 300px;
      background: linear-gradient(170deg, #003a5d, #94c7e6);
      background-size: 500% 100%;
    
      animation: warpedBackground 1s ease infinite;
    }
    <div id="gradientsquare"></div>

    Make it smaller than the div:

    @keyframes warpedBackground { 
        0%{background-position:0% 50%}
        50%{background-position:100% 50%}
        100%{background-position:0% 50%}
    }
    
    #gradientsquare {
      border:1px solid;
      width: 300px;
      height: 300px;
      background: linear-gradient(170deg, #003a5d, #94c7e6);
      background-size: 50% 100%;
      background-repeat:no-repeat;
      
      animation: warpedBackground 1s ease infinite;
    }
    <div id="gradientsquare"></div>