3 min read
In CSS, the
@keyframes command is used to create animations. Note that
@keyframes might not work on every browser. The table below specifies which version of different browsers can support
For example, consider the following code snippet:
@keyframes works by slowly transitioning from the beginning position or beginning styles to the modified positions or styles. To declare a keyframes animation,
@keyframes is used along with the name of your animation. Inside the brackets, you'll have to declare the "from" which is the starting position and the "to" which is the final position. "From" and "to" are the equivalent of "0%" and "100%" which is also an alternative you can use.
If you want to create an animation that is a bit more complex, i.e. has a couple of different stages, you can use different percentages such as "20%", "50%" etc. which can apply different styles or different properties at different stages in your animation. Consider the code below which uses different stages to change the colour of a div:
Notice the syntax used to give the animation properties to the div.
animation-duration. The following table contains a few of the essential CSS animation properties.
You can condense all of these properties into a single line using the
animation: property with the following syntax :
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
In our HTML section, we've created a button and passed the method "move()" to it to be called on a user's click. In function move(), we've assigned the element "animate" which is a div to the constant "elem". Setting the initial position variable (pos) to 50, we then create a new frame every 5 milliseconds (using
setInterval(frame, 5)). This will go on for as long as the position does not become 350. While the position is not 350, we increment the value of pos by 1. The only thing left to do is to assign the new positions to the element.