DEV Community

Cover image for The Easy Way To Do Basic CSS Animations
Pete
Pete

Posted on

The Easy Way To Do Basic CSS Animations

Do animations run automatically once the page loads? YES.

Animation in CSS sounds like a cool thing that manages to be complex at the same time, but an animation is just a change of a CSS property(e.g height) from one value to another. Simple.

Defining Animations

To define a CSS animation, you must specify some keyframes. A keyframe just contains the styles the element you want to animate will have at different times.
You also use keyframes to define the name of an animation. Look at the code snippet below.

@keyframes demo-animation {
  from {
    height: 24px;
  }
  to {
    height: 48px;
  }
}
Enter fullscreen mode Exit fullscreen mode

Code breakdown

The code snippet above will animate the height of any element from 24px to 48px and the animation's name will be demo-animation
In other words, when the animation starts, the height of the element you animate will be 24px and when the animation ends the height will be 48px.

Applying an Animation To an Element

If we want to use the animation we defined on an element with an id animated-element, we simply set the element's animation-name property to demo-animation (the name of the animation that we defined with keyframes).
Look at the code snippet below.

#animated-element {
  animation-name: demo-animation;
  animation-duration: 2s;
}
Enter fullscreen mode Exit fullscreen mode

Code breakdown

animation-name is a CSS property whose value must be a CSS animation that has been defined somewhere with keyframes

demo-animation is the name of the animation. That's what we are passing to animation-name

animation-duration is another CSS property that dictates how long the animation will last. Setting it to 2s means that when the animation starts, the height of the element will be 24px and after two seconds, the height of the element will be 48px.

There are other properties you can assign to an element that affect how the animation you have defined will be run. They include:

  1. animation-delay - the amount of time to wait before the animation starts running.

  2. animation-iteration-count - the number of times the animation should run.

  3. animation-direction - whether the animation should play from start-to-end or from end-to-start. Its values are normal(default), reverse, alternate and alternate-reverse.

You can look the other properties up on MDN

Note that animation properties(CSS properties that start with "animation-") are not to be used inside keyframes. They are to be used inside the style ruleset of the HTML element or elements you want to animate.

Top comments (0)