wordpress css

How to Add Keyframe Animations in WordPress

Last Updated on April 24, 2022 by WP Knowledge Hub

Animations to make your website more dynamic, and one of the easiest way to add a lightweight animation is to use Keyframes.

Understand the CSS Properties for Keyframe Animations

Before you start, these are the important properties to know when creating a CSS animation:

  • @keyframes: Specifies the styles that will be applied to the element through the animation.
  • animation-name: Creates a name you can use to reference the animation elsewhere in your code.
  • animation-duration: Defines how long the animation should run.
  • animation-delay: States how long an animation should wait to begin once the page is loaded.
  • animation-iteration-count: Notes how many times the animation should run.
  • animations-direction: States in what direction the animation should run.
  • animation-timing-function: Determines the speed curve of the animation.
  • animation-fill-mode: Specifies a style for the element when the animation is not playing.
  • animation: A shorthand property for binding keyframes to elements.

The most important of these properties to understand is the ‘keyframe.’ This term comes from hand-drawn animation processes, where the main frame was called the keyframe and others were drawn to lead into or out of it. 

Here, the @keyframe is telling the element to change 4 times:

@keyframes example {
  0%   {background-color: red;}
  25%  {background-color: green;}
  50%  {background-color: blue;}
  100% {background-color: orange;}

The example above says that it will change background color at a quarter way through the length of the animation, and then again at the next quarter, and so on until it’s done.

Creating the CSS to Animate an Element

In order for the animation to actually work, you would need to create a custom class explaining to WordPress that you want to use this animation somewhere. It would look something like this:

.your-custom-class {
  animation-name: example;
  animation-duration: 10s;
  animation-iteration-count: infinite;

Here, we’re declaring the animation’s name and telling the class we created that the animation should loop infinitely every 10 seconds.

This is what the final code would look like with added padding and a few alignment extras:

@keyframes example {
  0% { background-color: red; }
  50% { background-color: green; }
  50% { background-color: blue;}
  100% { background-color: orange; }

.your-custom-class {
	color: white;
	 width: 100%;
  padding: 100px;
	text-align: center;
  animation-name: example;
  animation-duration: 10s;
	animation-iteration-count: infinite;
	background-color: darkcyan;

In this example, adding the ‘your-custom-class‘ class to an HTML element will animate it using the keyframe animation we created:

This is what it looks like!