What is animation in CSS? How do you set it?
Animation in CSS is a mechanism that lets you smoothly change CSS property values over time (color, size, position, opacity, etc.) without JavaScript.
A CSS animation is defined using two parts:
1) Describing keyframes with @keyframes
css
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}from → the starting state
to → the ending state (percentages also work: 0%, 50%, 100%)
2) Applying the animation to an element
css
.box {
animation: fade 2s ease-in-out forwards;
}Where:
| Property | What it sets |
|---|---|
animation-name | the animation's name (fade) |
animation-duration | duration (2s, 500ms) |
animation-timing-function | the easing curve (e.g. ease, linear, ease-in-out) |
animation-iteration-count | number of repeats (1, infinite) |
animation-delay | delay |
animation-direction | direction (normal, reverse, alternate) |
animation-fill-mode | behavior before/after the animation (forwards, backwards, both) |
Summary
CSS animation is created like this:
- Describe the keyframes with
@keyframes - Assign the animation to an element with
animation
No JS, just CSS.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.