Animations in CSS can be used to add make elements more dynamic within a webpage and add movement or actions within the page. You can use CSS animations to change the style of an element easily within a webpage.
We can set the animation to use on an element by using the 'animation-name' property. The animation applied to an element with the id of 'myElement' is called 'example'. The 'animation-duration' is used to set how long the animation should take from start to end.
#myElement {
animation-name: example;
animation-duration: 4s;
}
The below code snippet shows creating the animation called 'example' using the '@keyframes' within CSS. The animation below will change an element's background color from the colour red to the colour yellow.
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
Obviously, there are different browsers, and people use different browsers to open webpages. CSS animations are a newer functionality available in CSS, and therefore is not directly supported in all browsers. The below code shows the same animation created above, but also specifying a browser type prefix so that different browsers can render/support the animation. In order, the browsers supported are Chrome, Firefox, Opera. Animations may not work in older browsers (such as IE 9). As well as the multi-browser support code below, you also need to generic animation creation code, as shown above.
@-webkit-keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
@-moz-keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
@-o-keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
The 'from' and 'to' keywords are no the only way to specify an animation. Percentages can be used to add additional steps within an animation. The below code snippets shows an animation that changes the background from red, to yellow, to blue, and then to green. These percentages can be any number that is a valid percentage, any number from 0 to 100. This can allow you to change the timing of an animation too.
@keyframes example {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
There are many different properties that you can change when using animations in CSS. Two of those properties are shown below, the delay and iteration count. The delay property determines how long after the page has loaded that the animation will start. The iteration count determines how many times the animation will play, this can be any whole number or the word 'infinite' which means the animation will loop forever.
animation-delay: 4s;
animation-iteration-count: 2;
This article was originally posted on my website: https://acroynon.com/
Top comments (0)