Skip to main content

CSS Animations

Moving or restyling an element over time does not require JavaScript, because CSS can animate HTML elements on its own.


What are CSS Animations?

With an animation, an element shifts gradually from one style to another, and neither the number of CSS properties involved nor the number of changes is limited.

Keyframes come first: they describe the styles an element should have at particular moments, and a CSS animation cannot run until they exist.


CSS animation-name and animation-duration

Two properties get an animation going. animation-name labels it, while animation-duration states how long one run takes. Leave the duration out and nothing animates, since its default value is 0s (0 seconds).


CSS @keyframes Rule

Styles placed inside a @keyframes rule mark the moments the animation passes through, and the element moves gradually from its current style towards each new one.

None of this has any effect until the animation is bound to an element.

Example

Here a <div> element is bound to "myAnimation". Over 4 seconds its background color fades from red to yellow. The keywords from and to stand for 0% and 100%.

Prompt
Create a CSS animation that gradually changes a 100x100px div's background color from red to yellow over 4 seconds, using @keyframes with "from" and "to" keywords along with animation-name and animation-duration properties.
Output: complete HTML page

Percentage keyframes

Percentages can replace from and to, and they allow any number of style changes. In this case the background color changes at 0%, 25%, 50%, and 100%.

Prompt
Create a CSS animation using @keyframes with percentage steps (0%, 25%, 50%, 100%) to change a 100x100px div's background color through red, yellow, blue, and green over 4 seconds.
Output: complete HTML page

Color and position

Keyframes at 0%, 25%, 50%, 75%, and 100% set both a background color and a position here, so the <div> element travels around a square path while its color changes.

Prompt
Create a CSS animation using @keyframes with percentage steps (0%, 25%, 50%, 75%, 100%) that changes both the background color and position of a 100x100px relatively-positioned div, moving it in a square path while cycling through red, yellow, blue, green, and back to red over 4 seconds.
Output: complete HTML page