CSS Animation
CSS animations allow you to create dynamic and visually engaging effects on web elements without the need for JavaScript. With CSS animations, you can smoothly transition between different property values over a specified duration, making it possible to animate changes in size, position, color, opacity, and more.
CSS animations are achieved using the @keyframes
rule, which defines the animation sequence by specifying intermediate stages or “keyframes” at different percentages of the animation’s duration.
Here’s the basic syntax for creating a CSS animation:
@keyframes animationName {
0% {
/* CSS properties at the beginning of the animation */
}
50% {
/* CSS properties halfway through the animation */
}
100% {
/* CSS properties at the end of the animation */
}
}
/* Apply the animation to an element */
.element {
animation-name: animationName;
animation-duration: 2s;
animation-timing-function: ease;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: normal;
animation-fill-mode: forwards;
animation-play-state: running;
}
Let’s break down the animation properties:
animation-name
: Specifies the name of the keyframes animation defined with@keyframes
.animation-duration
: Sets the duration of the animation in seconds (s) or milliseconds (ms).animation-timing-function
: Specifies the timing function that defines the animation’s acceleration or deceleration. Common values includeease
(default),linear
,ease-in
,ease-out
, andease-in-out
.animation-delay
: Sets the delay before the animation starts, specified in seconds (s) or milliseconds (ms).animation-iteration-count
: Defines the number of times the animation should repeat. Use a number orinfinite
.animation-direction
: Determines whether the animation should play in the normal direction (normal
) or reverse direction (reverse
) on each iteration.animation-fill-mode
: Specifies how the element should be styled before and after the animation. Options includenone
(default),forwards
,backwards
, andboth
.animation-play-state
: Controls whether the animation is running or paused. Options arerunning
(default) andpaused
.
Here’s a simple example of scaling an element using CSS animation:
@keyframes scaleAnimation {
0% {
transform: scale(1);
}
100% {
transform: scale(1.5);
}
}
.element {
width: 100px;
height: 100px;
background-color: blue;
animation-name: scaleAnimation;
animation-duration: 2s;
animation-timing-function: ease;
animation-iteration-count: infinite;
}
In this example, the .element
will continuously scale up and down with a duration of 2 seconds, creating a pulsing effect.
CSS animations are a powerful tool for creating interactive and engaging web experiences. They can be combined with other CSS properties and selectors to build complex and sophisticated animations without the need for JavaScript. However, it’s essential to use animations judiciously, as excessive or distracting animations can negatively impact user experience.