Search code examples
csscss-transitionswebkit-transform

Simultaneous CSS animation and spin transition


<style> 
div
{
width:50px;
height:100px;
background:red;
position:relative;
animation:myfirst 5s infinite alternate;
-webkit-animation:myfirst 5s infinite alternate;
}

@keyframes myfirst
{
0%   { left:0px; top:0px;}
25%  { left:200px; top:0px;}
50%  { left:200px; top:200px;}
75%  { left:0px; top:200px;}
100% { left:0px; top:0px;}
}


@-webkit-keyframes myfirst 
{
0%   { left:0px; top:0px;}
25%  { left:200px; top:0px;}
50%  { left:200px; top:200px;}
75%  { left:0px; top:200px;}
100% { left:0px; top:0px;}
}


</style>


<body>

<div></div>

</body>

Is it possible to add some sort of a rotate transition to this? I've tried adding the code to the div declaration and creating another selector, none of these appeared to work.


Solution

  • You should add and define another animation, perhaps like so:

    @keyframes rotate
    {
    from {
            transform: rotate(0deg);
        }
    to { 
            transform: rotate(360deg);
        }
    }
    

    And then add the animation to your element, separating it with a comma:

    animation:myfirst 5s infinite alternate, rotate 2.5s linear infinite;
    

    In this example note the following things:

    1. 2.5s I chose this to make two complete rotation in one go of your first animation, I thought it looked smoother.

    2. linear gives you the feeling of endless rotation in the void. Try other functions if you don't want this effect.

    3. I didn't put alternate because we want the element to spin continuously.

    Demonstration