Animations in CSS

You can create some amazing animation using CSS itself.

Animation is all about changing one style to another at certain intervals or times For doing that, first and foremost thing which we need to learn is @ keyframes.

Animations in CSS (Cont...)

Let's understand the keyframes syntax first

Animations in CSS (Cont...)

animation property is used to bind keyframes with a particular element. For example, suppose I want to move my element 500px left in four seconds.

Animations in CSS (Cont...)

We can also pass percentage in keyframes rule and make some amazing animations.
For example, suppose I want on change the background-color of an element.

// HTML
<div class="element1">change color</div>


//CSS
.element1 {
  background: black;
  animation: change 4s;
  text-align: center;
  color: white;
}

@keyframes change {
  0% { background-color: black; }
  25% { background-color: red; }
  50% { background-color: yellow; }
  75% { background-color: green; }
  100% { background-color: blue; }
}

Animations in CSS (Cont...)

One thing you might noticed here is that I'm using animation property only and passing multiple values in that.

 

Like animation: move 4s;

 

This is because animation is a shorthand for setting all animation properties

Animations in CSS (Cont...)

You can also specify the delay in your animation using animation delay property.

It specifies a delay before the start of an animation.

So far we have noticed that our animation only happens only once.

This is becuase we haven't applied the animation-iteration-count property.

It specifies the number of times an animation should run.

For Example, animation-iteration-count: 5
(You can also pass infinite)

Animations in CSS (Cont...)

Creating a smooth animation is important and we have animation-timing-function property for that.

This property specifies the speed curve of an animation. There are many functions that you can pass in this

 

You can pass following values in animation-timing function:

  • ease (slow start, then fast, then slow)
  • linear (same speed)
  • ease-in (slow start)
  • ease-out (slow end)
  • ease-in-out (slow start and slow end)
  • cubic-bezier (customizable)

Animations in CSS (Cont...)

One thing to note here is that animation do not affect element before or after the keyframes.

 

In order to persist the styling based on last or first keyframe, we have animation-fill-mode.

 

It accepts following value:

  • forwards (element will retain last keyframe styling).
  • backwards (element will get the first keyframe value even in animation-delay period).
  • both (both of the above).

Animations in CSS (Cont...)

Instead for using different animation properties you can use shorthand "animation" only.

For example:

Animations in CSS (Cont...)

Run the code:

https://codepen.io/codeat100mph/pen/OJWYYvm

Animations in CSS

By Code 100mph

Animations in CSS

  • 212