CSS Animation Basics

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.

The below code snippet shows creating the animation called ‘example’ using the ‘@keyframes’ within CSS. The animation below will change an elements background color from the colour red to the colour yellow.

Obviously, there are different browsers, and people use different browsers to open webpages. CSS animations is 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). Aswell as the multi-browser support code below, you also need to generic animation creation code, as shown above.

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.

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.

Leave a Reply