Bringing Web Pages to Life with CSS Animations: A Step-by-Step Guide
Published: 2024-06-30 17:22:11

Animation is an art of creating an illusion of movement from still characters. It is a process that causes still characters to be rendered in such a way that they change form gradually. The term animation is derived from the word “anime”. Anime is a Japanese word that means “to move”, “or to give live”. 
Animations are very important in any field that requires visual presentation of results. They have become more prevalent in creating educational materials, advertising, marketing, simulation training, data visualization, game development and of course, in entertainment.
In web development, animations are used to add life our web pages. Animated elements can be more attention grabbing, interactive and can create better user experience than still characters. 
For instance;
•	Animations can be helpful in guiding users on how to navigate through the website. 
•	It may help them to know when to be a little patient (like the loading animation).
•	Can be helpful with providing feedback like letting them know that a message has been sent.
•	It can also make the page more beautiful and captivating, thereby ensuring that users spend more time on the page.
In CSS, animation is the gradual change in style or set of styles applied to an HTML element. To animate an element with CSS, you have to write the codes to define the animation properties, and define the keyframes for the steps to the implementation of the animations and the properties to be animated.

## CSS keyframes
Keyframes signifies start points, and end points for the specific animations/ transitions. 
Syntax

```
@keyframes animation-name {
        from {
            property: initial value;
            property2: initial value;
            etc.       
 }

        to {
            property: final value;
            property2: final value;
            etc.
        }
    }

```
This is to say that the styles applied in the “from” block, should gradually morph into the styles applied in the “to” block. The “from” and “to” keywords are not so commonly used. What you are most likely to come across or use will be percentage values.

```

    @keyframes animation-name {
        0% {
            property: value;
            property2: value;
            etc.
        }

        100% {
            property: value;
            property2: value;
            etc.
        }
    }

```
Percentage values allow you to have as many transitional points as you may be required to have. 

## CSS animation properties

## animation-name
This is the name of the animation. You can give your animation any name you like. This name will serve as the identifier when applying the keyframes and styles to the animated element.
Syntax

```
        animation: animate;
```
 Then use the name as the identifier for the keyframes

```

    @keyframes animate {
        0% {
            border-radius: 0;
        }

        100% {
            border-radius: 50%;
        }
    }

```
Using animation-name property alone, you will not see any animation. To effect animation, you will have to at least set duration for the animation.

## animation-duration

This is used to determine how long the animation should run. It is usually measured in seconds(s) or milliseconds(ms). 1000 milliseconds is equal to 1second.
syntax

```
        animation-duration: 10000ms;
```
or

```
        animation-duration: 10s;
```
**example**
HTML

```
        <div class="box"></div>
```
CSS

```
    .box {
        height: 300px;
        width: 300px;
        background-color: red;
        border-radius: 50%;
        animation: animate;
        animation-duration: 2s;
    }

    @keyframes animate {
        0% {
            border-radius: 0;
        }

        100% {
            border-radius: 50%;
        }
    }

```
The div will gradually change shape from a square to a circle in 2 seconds.

## animation-delay
If animation-delay is set to an animation, the animation will wait for the set time before it starts. If the animation is set to repeat, only the first instance will be delayed, the subsequent animations will not be delayed. The animation-delay property accepts negative values. Hence, delay of 2s will cause the animation to wait for 2 seconds, while animation-delay of -2s will cause the animation to start as though the animation has started 2 seconds ago.
**Syntax**
`Animation-delay: <time>;
`
example

```
   animation: animate;
        animation-duration: 2s;
        animation-delay: 0.5s;

```

## animation-play-state
animation-play-state enables you to pause or play animation as you may need to. When you pause an animation, the animation will remain at the point it was when pause was activated, and resume from the same place as soon as the state is switched to running. The two major values for this property is “paused” and running.
For example, you could set the animation-play-state of an animated element to pause when hovered on, or you can use JavaScript to dynamically change the animation state based on interaction
Example

```
.box {
        height: 300px;
        width: 300px;
        background-color: red;
        border-radius: 50%;
        animation: animate;
        animation-duration: 2s;
        animation-play-state: running;
    }

    .box:hover {
        animation-play-state: paused;
    }

    @keyframes animate {
        0% {
            border-radius: 0;
        }

        100% {
            border-radius: 50%;
        }
    }

```

## animation-iteration-count
This property is used to set the number of times that the animation will run. The values for this property must be a positive integer or infinite. The value of infinite will cause the animation to continue running till infinity.
Example

```
  .box {
        height: 300px;
        width: 300px;
        background-color: red;
        animation: animate;
        animation-duration: 2s;
        animation-iteration-count: 6;
    }

   

    @keyframes animate {
        0% {
            border-radius: 0;
        }

        100% {
            border-radius: 50%;
        }
    }

```
In this example, the animation will run for 2 seconds each, six times.

## animation-timing-function:
animation-timing-function is used to set the rate of change of speed over the duration of the animation. Values to this property include;
ease: speed increases towards the middle of the animation, then slows down towards the end. This is the default value;
ease-in: starts slows, then becomes fast to the end
ease-out: starts quickly, then slows down
ease-in-out: starts slowly, seeds up then slows down again
linear: this will ensure that the speed is even all through.
steps(): makes stops according to the number of steps set
cubic-bezier(): used to set custom speed rates.

## animation-direction
animation-direction is used to set whether the animation should play forward, backward, or alternate between the two. Values to this property include;
normal: The animation will play forward.
reverse: The animation will play backward.
alternate: The animation will play forward on the first cycle, then backward on the second cycle, and so on.
alternate-reverse: The animation will play backward on the first cycle, then forward on the second cycle, and so on.

## animation-fill-mode
animation-fill-mode sets the style of the element after the animation is completed. It determines if the element will go back to its original style before the animation, or take up one of the styles specified in the animation keyframes. Values for the animation-fill-mode property include;
**forwards:** The animation will apply the styles from the last keyframe to the element after the animation executes.
**backwards:** The animation will apply the styles from the first keyframe to the element before the animation executes.
**both:** The animation will apply the styles from the first keyframe to the element before the animation executes and the styles from the last keyframe to the element after the animation executes.

## animation shorthand property
The animation shorthand property is a CSS property that allows you to define multiple animation properties in a single declaration. It is a concise way to define animations, making it easier to write and maintain code.
**Syntax**
CSS


```
        animation: <name> <duration> <timing-function> <delay> <iteration-count> <direction> <fill-mode> <play-state>;
```
**Example**

```
        animation: animate 2s linear 1s 3 alternate forwards running;   
```
It is not compulsory to use all the values. Default values will be applied in place of the omitted values.

## Multiple CSS animations on the same element:
You can apply multiple animations to the same element. All you have to do is separate the values with a comma.
**Example**

```
animation: animate-one 2s linear 1s 3 alternate forwards running, 
         animate-Two 4s steps(5) 4s 3 reverse forwards running;

```

## Illustration
To illustrate all we have been learning so far, we are going to make a simple text typing animation example.
To start with, we create an html page with a simple short text.
**HTML**

```
    <h1>CSS ANI<span>MA</span>TION.</h1>
```
Then to add styles, we add some styles to the body tag to remove margins and add background color.
**CSS**

```
  body {
        margin: 0;
        padding: 0;
        color: tan;
        background-color: rgb(2, 2, 33);

    }

```
Add basic styles to the h1 tag;

```
    h1 {
        overflow: hidden;
        white-space: nowrap;
        font-family: consolas;
        border-right: 4px solid tan;
        width: 14ch;
        margin-left: 50px;
        font-size: 6rem;	
    }

```
The hidden overflow will ensure we are unable to see what text venture outside the width of the h1. We set the white-space to no-wrap, so that all our text will be on a single line, and the width we set to 14 characters because that is the total number of characters we want to implement the typing animation on. Next, we add out animation styles to the h1 styles.
**CSS**

```
    h1 {
        animation-name: type;
        animation-duration: 3s;
        animation-timing-function: steps(14);
        animation-fill-mode: forwards;
        animation-iteration-count: 5;
        animation-direction: alternate;
        overflow: hidden;
        white-space: nowrap;
        font-family: consolas;
        border-right: 4px solid tan;
        width: 14ch;
        margin-left: 50px;
        font-size: 6rem;
    }


```
Here, the animation name is type, the name is used as identifier for the keyframes

```

   
    @keyframes type {
        0% {
            width: 0ch;
            border-right: 4px solid tan;

        }

        99% {
            width: 15ch;
            border-right: 4px solid tan;

        }

        100% {
            width: 15ch;
            border-right: none;

        }
    }


```
The animation will last for 3 seconds, and it will make 15 moves, one move per character within a time frame of three seconds. This will happen 5 times as we have set the iteration count to 5. The animation will also go as though the typed text is erased and rewritten a couple of times because we have set the direction to alternate. To illustrate animation play state, we will add a hover effect that will cause the animation to pause when we hover on the animation.

```
h1:hover {
        animation-play-state: paused;
        filter: hue-rotate(60deg);

    }
```
We can also add another animation with a few styles to the span tag with the animation shorthand property.

```
 h1 span {
        animation: rotate-hue 1s linear 2s infinite normal forwards;
        text-shadow: 0 5px 15px rgb(114, 255, 6);
        -webkit-text-stroke: 1px rgb(250, 0, 79);

    }

    @keyframes rotate-hue {
        0% {
            filter: hue-rotate(0deg);

        }

        100% {
            filter: hue-rotate(360deg);

        }
    }
```
**Output**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ayemelg9vl9yyrflpj57.gif)






## Advantages of CSS animations
1.	Flexibility : CSS animations can be used to animate a wide range of properties, including transforms, colors, and more.
2.	Customizable : CSS animations can be customized using various timing functions, delays, and iteration counts.
3.	Interactive : CSS animations can be interactive, responding to user input and hover states.
4.	No JavaScript required : CSS animations can be created without any JavaScript code.
5.	Improved user experience : CSS animations can enhance the user experience by providing visual feedback and smooth transitions.
6.	Cross-browser support : CSS animations are widely supported by modern browsers, including Chrome, Firefox, Safari, and Edge.

## Disadvantages of CSS animation
1.	Browser compatibility issues: While CSS animations are widely supported, there may be compatibility issues with older browsers.
2.	Performance issues with complex animations: Complex CSS animations can lead to performance issues, such as slow frame rates or lag.
3.	Limited support for conditional animations: CSS animations have limited support for conditional animations, making it difficult to animate elements based on specific conditions.
4.	Limited support for complex animations: CSS animations are best suited for simple animations, and complex animations may require JavaScript.

## Cautions to take when animating elements:
1.	Consider accessibility: Ensure animations don't cause accessibility issues, such as seizure triggers or distracting visuals.
2.	Avoid over-animating: Too many animations can cause visual overload and slow performance.
3.	Be cautious with animation durations: Long animation durations can lead to slow performance and visual lag.
4.	Be mindful of browser support: Ensure animations work across different browsers and versions.
5.	Note that not all CSS properties can be animated. Some CSS properties that cannot be animated are;
1)	display
2)	overflow
3)	position (except for position: fixed which can be animated)
4)	z-index
5)	visibility (except for toggling between visible and hidden)
6)	cursor
7)	pointer-events 
8)	box-sizing
9)	caret-color (except in Firefox)
10)	unicode-bidi (except in Firefox)
11)	writing-mode (except in Firefox)
12)	direction
13)	user-select
14)	nav-index
15)	tab-size
16)	shape-image-threshold (except in Firefox)
17)	shape-margin (except in Firefox)
18)	clip-path (except in Firefox)
19)	filter (except in Firefox)
20)	backdrop-filter (except in Firefox)

6.	Check the MDN documentation or other resources for the most up-to-date information on animatable properties, as browser support and specifications can change over time.

## Conclusion
In conclusion, CSS animations are a versatile tool that can be used to create a wide range of effects, from subtle interactions to complex animations. By leveraging the techniques and properties discussed in this article, developers can create web pages that are not only visually stunning but also provide a rich and engaging user experience.