Search code examples
csscss-transitionsgradientanimated

animating one color of a gradient continuously with css


saw some similar questions here but can't seem to figure out this one in particular.

I have a gradient that's black on top and blue on the bottom. I want the blue to fade to several different colours on a continuous loop, but the black to remain in place. like this: https://i.sstatic.net/6k9EN.gif

saw some demos like this one where the gradient animates continuously but it's just a large gradient being shifted vertically with keyframes which wouldn't work for me. Wondering if anyone could recommend a solution.

Here's the unanimated code so far: http://jsfiddle.net/ssccdd/9qA3L/

body{
      background: -moz-linear-gradient(top, #000000 80%, #3300FF 100%);
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(100%,#7db9e8));
      background: -webkit-linear-gradient(top,  #1e5799 80%,#3300FF 100%);
      background: -o-linear-gradient(top,  #000000 80%,#3300FF 100%);
      background: -ms-linear-gradient(top,  #000000 80%,#3300FF 100%);
      background: linear-gradient(to bottom,  #000000 80%,#3300FF 100%);
      filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#3300FF',GradientType=0 );
      background-attachment: fixed;

}


Solution

  • You might not be able to animate gradient colors, but you can animate the background color.

    So, in your case, have an unchanging linear gradient going from black to transparent. Then change the background color using CSS transitions.

    Here's a working example: http://jsfiddle.net/qSJa8/

    I had to include javascript to switch from one color to another:

    var classes = [ "stop1", "stop2", "stop3", "stop4" ];
    
    var stopIndex = 0;
    var lastClass = classes[0];
    window.setInterval(function() {
        ++stopIndex;
        if(stopIndex >= classes.length) {
            stopIndex = 0;
        }
        var newClass = classes[stopIndex];
        $('#sampleDiv').removeClass(lastClass).addClass(newClass);
        lastClass = newClass;
    
    }, 2000);
    

    And the css:

    #sampleDiv {
        height:300px;   
        background-image: linear-gradient(180deg, black, black 50%, transparent);
        transition: background-color 2s;
    }
    
    .stop1 {
        background-color:blue; 
    }
    
    .stop2 {
        background-color:purple;
    }
    
    .stop3 {
        background-color:green;
    }
    
    .stop4 {
        background-color:yellow;
    }