In this article, we will explain the very basics of CSS animations along with a demonstration of how to add a floating animation. CSS animations need the following.
- The animation declaration.
- The keyframes which defines the properties for getting animation. It also provides properties which says when and how they get animated.
Basically Animation is the shorthand property for the following properties: animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state. For this article, we will be using animation-name, animation-duration, animation-iteration-count, animation-timing-function.
- animation-name: Floating (this refers to @keyframe defined below).
- animation-duration: 3s (this refers to the numbers of seconds your animation will take from start to finish).
- animation-iteration-count: Infinite (the number of loops for your animation before stopping).
- animation-timing-function: ease-in-out (The timing for begin animations and end animation).
You can combine them under same keyword as shown in the following.
animation: floating 3s ease-in-out infinite
Let us talk about @keyframes. It give the control over animation. You can change your animation as you like by using this property. First start with the @keyframes rule followed by name of the animation (In this case, it is “floating”). Inside the @keyframes, you can see 3 percentage values have been declared. It is followed by a code snippet containing properties and their values. These percentages represent the breakpoints along the animation sequence.
- The 0% selector contains a block that execute at the beginning of the animation.
- The 50% selector contains a block that execute at the halfway point.
- The 100% selector contains a block that execute once animation is complete.
At each of these break points, we have property
transform. The transform property which allows the user to rotate, skew, scale, or translate a given element. In this case, we will be using translate property. Basically
translate helps us to place things vertically and horizontally.