Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How do I animate an element to swing in CSS3?

How do I animate an element to swing in CSS3?

Problem

Since I saw the Treahouse website and the sign effect swinging in the tree, I have been trying to reproduce it.

.box{
    width:50px; height:50px;
    background: blue;
    box-shadow: 0 0 5px blue;
    margin:100px;
    float: left;
    -moz-animation: 3s ease 0s normal none infinite swing;
    -moz-transform-origin: center top;
}

But it won’t swing.

Here’s a demo on JS Fiddle.

I also tried a modification of that.

bod{
  background:blue;
}
.box{
    width:50px; height:50px;
    background: yellow;
    box-shadow: 0 0 10px red,0 0 25px red inset;
    margin:100px;
    float: left;
    -moz-animation: 3s ease 0s normal none infinite swing;
    -moz-transform-origin: center top;
    border-radius:50%;
}
@-webkit-keyframes swing {
 from {
   left: -2px;
 }
 to {
   left: 200px;
 }
}

But that doesn’t work either. See that demo on JS Fiddle.

Problem courtesy of: Toni Michel Caubet

Solution

You might want to try using transform: rotate() and like in sven's comment change the prefix to "-moz-" not "-webkit-" because you are using mozilla animations.

Here is an example: http://jsfiddle.net/gVCWE/14/

.box{
    width:50px; height:50px;
    background: yellow;
    border: 1px solid black;
    margin:100px;
    position: relative;
    float: left;
    -moz-animation: 3s ease 0s normal none infinite swing;
    -moz-transform-origin: center top;
    -webkit-animation:swing 3s infinite ease-in-out;
    -webkit-transform-origin:top;
}

@-moz-keyframes swing{
    0%{-moz-transform:rotate(-3deg)}
    50%{-moz-transform:rotate(3deg)}
    100%{-moz-transform:rotate(-3deg)}
}
@-webkit-keyframes swing{
    0%{-webkit-transform:rotate(-3deg)}
    50%{-webkit-transform:rotate(3deg)}
    100%{-webkit-transform:rotate(-3deg)}
}

Also, the reason they have -moz-transform-origin: center top; is so it rotates around the top so using left: -2px to left: 200px will not make sense.

EDIT: new jsfiddle example: http://jsfiddle.net/gVCWE/20/

Solution courtesy of: Caleb Doucet

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

How do I animate an element to swing in CSS3?

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×