Search code examples
csscss-animations

Play multiple CSS animations at the same time


How can I have two CSS animations playing at different speeds?

  • The image should be rotating and growing at the same time.
  • The rotation will cycle every 2 seconds.
  • The growth will cycle every 4 seconds.

Example Code:

.image {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 120px;
    height: 120px;
    margin:-60px 0 0 -60px;
    -webkit-animation:spin 2s linear infinite;
    -webkit-animation:scale 4s linear infinite;
}

@-webkit-keyframes spin { 
    100% { 
        transform: rotate(180deg);
    } 
}

@-webkit-keyframes scale {
    100% {
         transform: scaleX(2) scaleY(2);
    }
}

http://jsfiddle.net/Ugc5g/3388/ - only one animation (the last one declared) plays.


Solution

  • TL;DR

    With a comma, you can specify multiple animations each with their own properties as stated in the CriticalError answer below.

    Example:

    animation: rotate 1s, spin 3s;
    

    Original answer

    There are two issues here:

    #1

    -webkit-animation:spin 2s linear infinite;
    -webkit-animation:scale 4s linear infinite;
    

    The second line replaces the first one. So, has no effect.

    #2

    Both keyframes applies on the same property transform

    As an alternative you could to wrap the image in a <div> and animate each one separately and at different speeds.

    http://jsfiddle.net/rnrlabs/x9cu53hp/

    .scaler {
        position: absolute;
        top: 100%;
        left: 50%;
        width: 120px;
        height: 120px;
        margin:-60px 0 0 -60px;
        animation: scale 4s infinite linear;    
    }
    
    .spinner {
        position: relative;
        top: 150px;
        animation: spin 2s infinite linear;
    }
    
    
    @keyframes spin { 
        100% { 
            transform: rotate(180deg);
        } 
    }
    
    @keyframes scale {
        100% {
             transform: scaleX(2) scaleY(2);
        }
    }
    <div class="spinner">
    <img class="scaler" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
    <div>