In this lesson, we style a static element and turn it into a loading animation using
We look at how to write a basic set of
@keyframes and how to apply it to a static element turning it into a loading animation.
Jhey Tompkins: [0:00] Start by creating an element for our loading animation. Then we need to create some styles for our loader. Let's start by adding a solid 10px white border. Let's make our loading animation round with border-radius: 50% and let's increase the height and width to 10vmin.
[0:23] Spinning this element currently will give no visual indication anything is happening. Let's change the border-left-color: hsl(280, 50%, 40%), and let's do the same for the right color.
[0:43] To make our element spin we need to define a set of keyframes. Here we name our keyframes spin. We can use the keywords from and to. These are equal to % and 100%. At the start of our keyframes we want our element to be rotated by 0deg and to do that we can use the transform. By the end of our keyframes we want the element to have spun 360deg.
[1:08] Now we need to apply the animation to our element. Define an animation-name: spin and apply an animation-duration. Here we have entered 1s, but any second or millisecond duration will work. Refresh our page and our element spun once, but we want our element to spin infinitely, so we can use animation-iteration-count with the keyword infinite. Now our element infinitely spins around.
[1:33] However, the speed isn't quite right. To change that we can update the animation-timing-function for our element. We want our element to continuously spin at the same speed, so we use the linear value. We can use the animation property as a shorthand to tidy us up. Value would be spin, which is the name, duration 1s, the iteration count infinite and timing function linear.
[1:55] If we remove those previous declarations and save, we can see that our element is still spinning as intended.
[2:00] We can also tidy up our keyframes as the initial state of our element matches the initial state of the keyframe. We can remove the declaration for the % and that gives us a basic loading animation using CSS.
[2:12] In review, we can use CSS animation to take a styled static element and create a loading animation. We've defined a set of keyframes that spins our element 360deg, that we animate infinitely and linearly one second of a time.
[2:26] For this example, we've opted to use the animation shorthand property and we've refactored our keyframes by removing the % declaration that matched the initial state of our element.