Currently On

The Blog

CSS3 Animations for Beginners

CSS3 Animations can be great and very simple to implement onto any website. In this post, I will break down what is required to create a simple CSS3 Animation with a handful of live examples.

See the Pen Floating Phone by Richard (@barkins) on CodePen.

Simple Example

See the Pen CSS3 Animation by Richard (@barkins) on CodePen.

Step 1: Style the Element

Pick an HTML element on your page you want to animate and apply the following styles to it:

#box {
  margin-top:50px;
  width:100px;
  height:100px;
  color:white;
  background:red;
  text-align:center;
  line-height:100px;
  font-family: sans-serif;  
  
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-name:boxy;
  animation-direction: alternate;
}

Step 2: Applying the Animation

Now the second part of the equation comes in. The part where you specific exactly what the animation does:

@keyframes boxy {
  0% {
    margin-left:50px;
  }  
  100%{
    margin-left:100px;
  }    
}

Lets Break it Down

When selecting an element to animate via CSS, here’s a list of animation properties available to you.

Property Name Definition Examples
animation-delay Specifies when the animation should start after the page loads. 0s, 3s, 10s
animation-direction Defines whether an animation should be reversed or alternate. normal, reverse, alternate
animation-duration Indicate how long an animation should take to complete its cycle. 3s, 5s, 120ms
animation-interation-count Specify how many times an animation repeats. 1, 3, 5, infinite
animation-timing-function Configure how the animation transitions between each keyframe. ease, ease-in, ease-out, ease-in-out, linear
animation-name The same name paired with @keyframes bouncy-ball, animated-item

Bouncing Text

CSS

#animate {  
  font-family:sans-serif;
  font-size:24px;
  
  animation-name:texty;
  animation-duration: 1s;
  animation-direction: alternate;
  animation-iteration-count: infinite; 
}

@keyframes texty {
  0% {
   /* transform: rotate(90deg);*/
    margin-top:0px;
  }
  100% {
   /* transform: rotate(0deg);*/
    margin-top:100px;
  }  
}

See the Pen CSS3 Animation: Text by Richard (@barkins) on CodePen.

Transform

One final element to consider within the @keyframes code is the transform property. It can be used to scale or rotate an element.

Here’s an examples of its usage:

@keyframes phone {
   0% {
    margin-top:-50px;    
    transform:scale(.5);    
  }
  
  50%{
    transform:rotate(360deg);
  }
  
  100%{
    margin-top:-75px;    
  }
}

I will leave you with one final thought. Although animations can be cool they can also be distracting, so just like so many things in HTML and CSS, just because you can do it, doesn’t mean you should.

CSS3