Codetips – CSS Animations

There are two methods of CSS animations, one is transitions and the other is Keyframes.

Transitions

Transitions are useful when we want to animate content when the user does something with it, for example on a hover.

If we have a simple anchored image that takes us to Twitter

<a href="https://twitter.com">img src="/images/social/twitter.png"/></a>

We can define some attributes for when the item is hovered over

a img {
height:40px;
width:40px;
}
a:hover>img {
height:60px;
width:60px;
}

This is all well and good but the item just jumps from 40px to 60px when we hover over it. If we introduce the transition attribute then we can glide from 40px to 60px

a img {
height:40px;
width:40px;
transition: height 0.5s, width 0.5s;
-webkit-transition: height 0.5s, width 0.5s;
}

a:hover > img {
height:60px;
width:60px;
transition: height 0.5s, width 0.5s;
-webkit-transition: height 0.5s, width 0.5s;
}

See, this is nice and smooth now. We could play about will all different things, you could bounce it to one side, or apply any CSS attribute to the animation. The key is though, it must have the style attribute in both the before and after hover code. If the attribute doesn’t have an original value it can’t transition to something else.

This is quite a hideous example but shows what you can achieve with transitions.

Keyframes

Keyframes can be beneficial when we need to run animations when the page has loaded, such as the new design on my personal site

What’s being done here is we tell the element we want to animation to take 2 seconds, to use the animation mode ease-in, start with no delay, run once, and use the keyframes named ‘one’.

animation: 2s ease-in 0s 1 one;
 @keyframes one {
  
0% {
    bottom: -10vh;
    opacity: 0;
    left:0px;
  }
  25%
  {
    left:200px;
  }
  50%
  {
    left:0px;
  }
  75%
  {
    left:200px;
  }
  100% {
    left :0px;
    bottom: 0vh;
    opacity: 1;
  }
}

We then set the style for our keyframe, and we can provide different styles for completion percentages. So when we’re 25% of the way through the image will be 200px to the left and then return to its 0px position. An important thing to remember about keyframes is that once they are complete, they will take on the style you’ve given it in the original design. So if we give the element an opacity of 1 but set it to opacity:0 in our keyframes it will jump back to opacity:1 when the keyframe is completed

Alex Written by: