Tutorials CSS Animations & Keyframes
Ch 45 / 60
Chapter 45 Intermediate 10 min read CSS

CSS Animations & Keyframes

CSS animations let elements move, fade, spin, and morph autonomously — no hover needed, no JavaScript required. You define the steps with @keyframes and apply them with the animation property. Unlike transitions that animate between two states, animations can have any number of steps, loop indefinitely, reverse direction, pause on hover, and apply styles before they start or after they finish.

What you'll learn
@keyframes — from/to and percentage steps
All 8 animation sub-properties
animation-direction — normal, reverse, alternate
animation-fill-mode — forwards, backwards, both
animation-play-state — pause on hover
10 real-world animation patterns

@keyframes — Defining Animation Steps

The @keyframes rule defines what an animation looks like at specific points during its duration. You can use from/to for simple two-state animations, or percentage values for multi-step sequences:

@keyframes slideFadeIn {
  from  { opacity: 0;  transform: translateY(20px); }
  to   { opacity: 1;  transform: translateY(0); }
}
Progress through animation duration →
0% / from
25%
50%
75%
100% / to
startend
CSS — @keyframes syntax
/* Two-state: from / to (= 0% / 100%) */
@keyframes fadeIn {
  from { opacity: 0; }
  to   { opacity: 1; }
}

/* Multi-step with percentages */
@keyframes bounce {
  0%, 100%{ transform: translateY(0); }
  25%     { transform: translateY(-20px); }
  50%     { transform: translateY(-10px); }
  75%     { transform: translateY(-15px); }
}

/* Multiple properties per step */
@keyframes slideFadeIn {
  from { opacity: 0; transform: translateY(30px); }
  to   { opacity: 1; transform: translateY(0); }
}

/* Per-step easing with animation-timing-function */
@keyframes bounce2 {
  0%, 100%{
    transform: translateY(0);
    animation-timing-function: cubic-bezier(.33,1,.68,1);
  }
  50% {
    transform: translateY(-24px);
    animation-timing-function: cubic-bezier(.32,0,.67,0);
  }
}

/* Shared keyframes between steps */
@keyframes pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50%      { transform: scale(1.15); opacity: .7; }
}

The animation Property

Once you define a @keyframes rule, you apply it using the animation shorthand or individual sub-properties. The shorthand order:

animation:  name  duration  timing  delay  count  direction  fill-mode  play-state;
name
duration
timing-fn
delay
iteration-count
direction
fill-mode
play-state
CSS — animation shorthand and sub-properties
/* Shorthand */
.el { animation: spin 1s linear infinite; }
.el { animation: fadeIn .6s ease-out .2s 1 normal forwards; }

/* Individual sub-properties */
.el {
  animation-name:             bounce;          /* @keyframes name */
  animation-duration:         1.2s;            /* how long one cycle takes */
  animation-timing-function:  ease-in-out;    /* speed curve */
  animation-delay:            0.3s;            /* wait before starting */
  animation-iteration-count:  infinite;       /* loops: 1, 2, infinite */
  animation-direction:        alternate;      /* normal|reverse|alternate|alternate-reverse */
  animation-fill-mode:        forwards;       /* none|forwards|backwards|both */
  animation-play-state:       running;        /* running|paused */
}

/* Multiple animations — comma separated */
.el {
  animation:
    float  3s ease-in-out infinite,
    gradshift 5s linear infinite;
}

/* Pause on hover */
.spinner       { animation: spin 1s linear infinite; }
.spinner:hover { animation-play-state: paused; }

Live Animation Demos

All animations below are running in pure CSS — no JavaScript. Each one is a real-world pattern you'll use regularly:

Spinner
1s linear ∞
Pulse
1.5s ease-in-out ∞
Bounce
1s ease-in-out ∞
Float
3s ease-in-out ∞
fadeInUp
1s ease-out forwards
Shimmer skeleton
1.8s linear ∞
CSS
Cursor blink
0.8s step-end ∞
❤️
Heartbeat
1.4s ease ∞
Orbit
2s linear ∞
Gradient shift
4s ease ∞
Progress bar
2s ease-in-out ∞ alt

animation-direction

Controls which way each cycle plays. alternate is especially useful for loops that should feel organic — the animation reverses on every other cycle instead of snapping back to the start:

nrm
normal
→ → →
rev
reverse
← ← ←
alt
alternate
→ ← → ←
a-r
alternate-reverse
← → ← →
CSS — direction, iteration, fill-mode, play-state
/* ── animation-direction ── */
.el { animation-direction: normal; }           /* default: 0%→100% each cycle */
.el { animation-direction: reverse; }          /* 100%→0% each cycle */
.el { animation-direction: alternate; }        /* 0%→100% then 100%→0% etc. */
.el { animation-direction: alternate-reverse; } /* 100%→0% then 0%→100% */

/* ── animation-iteration-count ── */
.el { animation-iteration-count: 1; }         /* run once — default */
.el { animation-iteration-count: 3; }         /* run 3 times */
.el { animation-iteration-count: infinite; }  /* loop forever */
.el { animation-iteration-count: 2.5; }       /* 2.5 cycles — stops mid-way */

/* ── animation-fill-mode ── */
.el { animation-fill-mode: none; }       /* default: reverts after end */
.el { animation-fill-mode: forwards; }   /* keeps final keyframe styles */
.el { animation-fill-mode: backwards; }  /* applies from keyframe during delay */
.el { animation-fill-mode: both; }       /* forwards + backwards combined */

/* ── animation-play-state ── */
.spinner       { animation: spin 1s linear infinite; }
.spinner:hover { animation-play-state: paused; }  /* pause on hover */
/* or via JS: el.style.animationPlayState = 'paused' */

animation-fill-mode — Styles Before & After

fill-mode is one of the most important — and overlooked — animation properties. Without forwards, an element that fades in will snap back to its original (invisible) state when the animation ends:

none
fill-mode: none
Snaps back
fwd
fill-mode: forwards
Stays visible ✓
both
fill-mode: both
Invisible during delay, stays after
forwards — the element keeps the styles from the last keyframe after the animation ends. Essential for entrance animations (fade-in, slide-in) where you don't want the element to disappear again.

backwards — applies the styles from the first keyframe during the animation-delay period. Without this, a delayed fade-in shows at full opacity before jumping invisible at start.

10 Real-World Animation Patterns

CSS — production-ready animation patterns
/* ── 1. Spinner ── */
@keyframes spin { to { transform: rotate(360deg); } }
.spinner {
  border: 3px solid rgba(0,0,0,.1);
  border-top-color: #264de4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* ── 2. Shimmer skeleton loader ── */
@keyframes shimmer {
  0%   { background-position: -200% 0; }
  100% { background-position:  200% 0; }
}
.skeleton {
  background: linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%);
  background-size: 200% 100%;
  border-radius: 4px;
  animation: shimmer 1.8s linear infinite;
}

/* ── 3. Fade + slide in on load ── */
@keyframes fadeInUp {
  from { opacity: 0; transform: translateY(24px); }
  to   { opacity: 1; transform: translateY(0); }
}
.hero-title   { animation: fadeInUp .6s ease-out both; }
.hero-subtitle{ animation: fadeInUp .6s ease-out .15s both; }
.hero-cta     { animation: fadeInUp .6s ease-out .3s both; }

/* ── 4. Float ── */
@keyframes float {
  0%,100% { transform: translateY(0); }
  50%     { transform: translateY(-12px); }
}
.illustration { animation: float 3s ease-in-out infinite; }

/* ── 5. Pulse (notification dot) ── */
@keyframes ping {
  0%   { transform: scale(1);   opacity: 1; }
  75%,100%{ transform: scale(2); opacity: 0; }
}
.notification-dot::before {
  content: '';
  position: absolute; inset: 0;
  border-radius: 50%;
  background: inherit;
  animation: ping 1.5s cubic-bezier(0,0,.2,1) infinite;
}

/* ── 6. Gradient animation ── */
@keyframes gradshift {
  0%,100% { background-position: 0% 50%; }
  50%     { background-position: 100% 50%; }
}
.hero-bg {
  background: linear-gradient(270deg,#264de4,#a855f7,#22c55e);
  background-size: 600% 600%;
  animation: gradshift 8s ease infinite;
}

/* ── 7. Typing cursor ── */
@keyframes blink {
  0%,100% { opacity: 1; }
  50%      { opacity: 0; }
}
.cursor {
  display: inline-block; width: 2px; height: 1em;
  background: currentColor;
  animation: blink .8s step-end infinite;
}

/* ── 8. Stagger hero items (class added via JS) ── */
.fade-item               { animation: fadeInUp .5s ease-out both; }
.fade-item:nth-child(2)  { animation-delay: .1s; }
.fade-item:nth-child(3)  { animation-delay: .2s; }
.fade-item:nth-child(4)  { animation-delay: .3s; }

/* ── 9. Pause on hover ── */
.animated:hover { animation-play-state: paused; }

/* ── 10. Reduced motion — always include ── */
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration:       .01ms !important;
    animation-iteration-count: 1 !important;
  }
}

Animation Sub-Properties Reference

Property Values Default
animation-name keyframe name, none none
animation-duration 0s, .6s, 1200ms… 0s
animation-timing-function ease, linear, ease-in/out, cubic-bezier(), steps() ease
animation-delay 0s, .3s, negative values 0s
animation-iteration-count 1, 3, infinite, 2.5 1
animation-direction normal, reverse, alternate, alternate-reverse normal
animation-fill-mode none, forwards, backwards, both none
animation-play-state running, paused running
animation (shorthand) name duration timing delay count direction fill-mode play-state —
Free Resource
CSS3 Cheat Sheet — All Properties & Animations
Complete reference covering all CSS animation sub-properties, @keyframes patterns and timing functions.
Download PDF

Try It Yourself

An interactive animation playground — edit the @keyframes and animation properties to experiment:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 45

Questions & Answers
Transitions: animate between exactly two states. Require an event trigger (hover, focus, class change). Cannot loop. Cannot have intermediate steps.

CSS Animations (@keyframes): run independently — no trigger needed. Support unlimited intermediate steps (0%, 25%, 50%…). Can loop infinitely. Can reverse direction. Can be paused. Can apply styles before start (backwards) or after end (forwards fill-mode).

When to use which:
— Transitions: interactive state changes — button hover, modal open, menu expand
— Animations: continuous motion — spinners, loading skeletons, floating illustrations, entrance animations, background effects

A common pattern combines both: a CSS animation for continuous floating, plus a CSS transition for the button that stops it on hover.
By default (fill-mode: none), an animation resets the element to its original CSS state when it finishes. This means a fade-in animation (from opacity:0 to opacity:1) will cause the element to snap back to invisible when it ends — completely defeating the purpose.

animation-fill-mode: forwards tells the browser to keep the styles from the last keyframe applied after the animation ends. The element stays at opacity:1 after fading in.

Use cases for forwards:
— Any entrance animation (fadeIn, slideIn, scaleIn) — you want the element to stay visible
— One-shot animations that land the element in a new position

Use cases for backwards:
— When you have an animation-delay and the element has a "from" state different from its initial CSS state. Without backwards, the element is visible at its normal state during the delay, then suddenly snaps to the "from" state when the animation starts — jarring. With backwards, the from-state applies immediately.

both = forwards + backwards combined — the safest choice for most entrance animations with a delay.
Normal infinite loop: each cycle always plays 0% → 100%, then immediately jumps back to 0% and plays again. This creates a visible "snap" at the loop point — fine for a spinner that rotates full circles, but jarring for a floating or pulsing animation.

alternate: odd cycles play 0% → 100%, even cycles play 100% → 0%. The animation flows smoothly in one direction, then reverses back in the other direction. No snap at the transition point.

@keyframes float { 0%,100%{translateY(0)} 50%{translateY(-12px)} }
— With normal: floats up-down then snaps back to start
— This specific example uses 0%/100% the same, so it already looks smooth with normal

More impactful for asymmetric animations:
@keyframes slide { from{translateX(0)} to{translateX(100px)} }
— normal infinite: slides right, snaps back left, slides right... (jerky)
— alternate infinite: slides right, slides back left, slides right... (smooth)
You can set animation-timing-function inside individual keyframe stops. The value applies to the segment from that keyframe to the next one:

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
    animation-timing-function: cubic-bezier(.33,1,.68,1); /* decelerate up */
  }
  50% {
    transform: translateY(-24px);
    animation-timing-function: cubic-bezier(.32,0,.67,0); /* accelerate down */
  }
}

— 0%→50%: easing is the value set at 0% (decelerate → feels like ball slowing at top)
— 50%→100%: easing is the value set at 50% (accelerate → gravity pulling ball down)

This creates a physically realistic bounce where the ball slows down rising and speeds up falling — much more convincing than a single easing across the whole animation.
Use comma-separated values in the animation property — each animation gets its own name, duration, easing and other settings:

.el { animation: float 3s ease-in-out infinite, gradshift 5s linear infinite; }

The two animations run completely independently — they have their own timelines, durations and iteration counts. This is how you layer multiple effects:
— A floating motion (3s cycle)
— A shifting gradient background (5s cycle)
— Both running at their own pace simultaneously

You can also comma-separate individual sub-properties:
animation-name: float, gradshift;
animation-duration: 3s, 5s;

Limitation: if both animations target the same property (e.g. both animate transform), they conflict — only one wins. Structure animations to target different properties, or use separate wrapper elements for conflicting transforms.
Multiple Choice Questions
Question 1 of 5
An entrance animation makes an element fade in. After it finishes with default settings, what happens?
Question 2 of 5
What does animation-direction: alternate do differently from normal?
Question 3 of 5
Which animation shorthand correctly makes an element fade in once, stay visible, and start after a 0.3s delay?
Question 4 of 5
How do you pause a CSS animation when the user hovers over the element?
Question 5 of 5
In a @keyframes rule, if you set animation-timing-function at the 0% keyframe, which segment does it apply to?
Chapter Summary
  • @keyframes name { }: defines animation steps with from/to or percentage values (0%, 25%, 50%…). Multiple properties can change at each step.
  • animation shorthand: animation: name duration timing delay count direction fill-mode play-state. Comma-separate for multiple simultaneous animations.
  • animation-fill-mode: forwards — essential for entrance animations. Keeps the final keyframe styles after the animation ends. Use both for delayed entrances.
  • animation-direction: alternate — smooth back-and-forth. Odd cycles forward, even cycles reverse. Avoids the snap of a normal infinite loop.
  • animation-play-state: paused — pause with CSS hover or JavaScript. The animation resumes exactly where it stopped when unpaused.
  • Per-step easing: set animation-timing-function inside a keyframe to control easing for that specific segment only — enables realistic physics-based bounce.
  • Key patterns: spinner (linear infinite), shimmer (background-position), fadeInUp (once forwards), float (alternate), stagger (nth-child delay), ping (scale + opacity to 0).
  • Multiple animations: comma-separate in one animation declaration. Animations cannot share the same property — use wrappers for conflicting transforms.
  • Reduced motion: always include @media (prefers-reduced-motion: reduce) to disable or simplify animations for vestibular disorder users.
~10 min read
Intermediate level
Chapter 45 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel