Overthunk

Quick Intro to CSS Keyframes & Animations

Make cool effects with CSS Keyframes and Animations

May 4, 2020


Contents

What is a Keyframe?

CSS Keyframes are really frickin’ cool 🎉

Now you’re probably wondering “Mani. What are CSS Keyframes.”.

Keyframes are a kind of CSS @ rule (like @media, @font-face) which allows you to define styles for specific points in your animation sequence. So rather than just saying that you want to transition from one style to another, you can specify exactly what the style should look like while it’s undergoing the transition.

This is especially useful when you’re trying to change the color of the text-shadow property for an element and you want to pick the colors that the animation goes through.

Setting Waypoints

So how exactly do we set these waypoints? We define a keyframe with @keyframes {name}. This named rule can then be used in an animation. Each @keyframes rule contains a list of selectors, which specify the percentage along the animation and a block for defining the style at that percentage.

The code snippet below is the most basic kind of keyframe where the from block is equivalent to 0% of animation progress and to is 100%.

@keyframes rainbow {
	from {
		...;
	}
	to {
		...;
	}
}

We can also specify an arbitrary number of waypoints not inluding 0% and 100%

@keyframes rainbow {
	10% {
		...;
	}
	20% {
		...;
	}
	40% {
		...;
	}
	75% {
		...;
	}
	96% {
		...;
	}
}

If the keyframe doesn’t include the start & end waypoints for the animation (0% / from and 100%/ to), the element will be animated from it’s initial state through the waypoints back to it’s initial state.

That’s enough theory. Let’s see some examples!!

The CodePen embed below shows an example of HTML that mimics the title of my website.

Now we’re going to add a keyframe that changes the color of the text-shadow every 20% of animation progress.

Hmmmm.. That didn’t really change anything. That’s because Keyframes by themselves are just style descriptors. We need to use them in an animation to have an effect.

Which brings us to:

Animation sub-properties

CSS Animations are also really frickin’ cool 🎉. They make this whole enterprise go round & round.

An animation has two parts - a description of the animation (duration, transition function etc.) and the keyframes that define the actual state of the animation at different points.

Let’s look at the sub-properties of an animation:

We can encapsulate all these properties into one using the animation shorthand.

For this post, we are going to configure a very simple animation. It is going to look like this -

animation: rainbow 4s ease 2s infinite reverse;

Let’s break this down into invidual sub-properties:

Et Voila 🥳🥳🥳!

We have now successfully animated an element using keyframes!

Please feel free to play around with the Code Pens and explore the cool world of CSS Animations!

Resources