Animations & transitions in React JS
Course: React JS Training
Topic: Animations & transitions
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Introduction: why movement matters in a web page
A page where every change happens in a single instant feels mechanical. A button that snaps from blue to dark blue, a menu that appears out of nowhere, a card that suddenly grows a shadow — all of these work, but they feel rough. Motion smooths these edges. A button that darkens gradually under the cursor tells the user "you are pointing at me". A spinner says "work is happening". A card that lifts a few pixels on hover says "I am clickable". Used well, movement gives feedback, guides attention and makes an interface feel finished.
CSS gives you two built-in tools for motion, and both run entirely in the browser without any JavaScript:
- Transitions answer the question: "when a style value changes from A to B, how should that change unfold over time?"
- Animations answer the question: "what scripted sequence of styles should play, for how long, and how many times?"
Both tools matter later in this course as well. React updates state and re-renders the interface, but React does not make things move smoothly — that is CSS's job. A class toggled by a component can trigger a CSS transition or animation, so understanding this sub-module makes your future framework work look polished instead of abrupt.
2. Transitions and animations in simple words
A transition is an instruction that says: "when this property changes from one value to another, do not jump — spread the change over a short time." Think of a light dimmer instead of a switch: the start point and the end point are fixed, and the transition only decides how smoothly you travel between them. A transition always needs two states — for example, a normal state and a hovered state — and it always needs something to trigger the change.
A keyframe animation is more like a short scripted film. You write a series of scenes ("at the start, be invisible and shifted left; at the end, be visible and in place"), and the browser plays the scenes in order. An animation can start by itself the moment the element appears, it can pause at points in the middle, it can repeat forever, and it does not need the user to hover or click anything.
The difference in one line: a transition reacts to a change that happens anyway, while an animation performs a sequence on its own.
3. Key terms you will meet in this sub-module
| Term | Meaning in plain words |
property | The style that changes, for example background-color or transform. |
| State | The condition that triggers a change: :hover, :focus, a class added by JavaScript, and so on. |
| Duration | How long one change or one cycle takes, written like 0.3s or 2s. |
| Timing function (easing) | The speed curve of the change: does it start fast and end slow, stay constant, and so on. |
| Delay | Waiting time before the change or the animation begins. |
| Keyframe | A snapshot of style values at one moment inside an animation. |
| Iteration | One full play-through of an animation. infinite means it never stops. |
| Fill mode | Which styles apply before an animation starts and after it ends. |
transform | Moves, scales, rotates or tilts an element without disturbing the page layout. |
opacity | How see-through an element is, from 0 (invisible) to 1 (fully solid). |
4. Transition syntax: the properties that control a transition
A transition is described by four pieces of information, each available as its own CSS property:
transition-property — which property or properties should be animated, for example background-color.
transition-duration — how long the change takes, for example 0.3s.
transition-timing-function — the speed curve, for example ease.
transition-delay — how long to wait before starting, for example 0s.
.button {
transition-property: background-color;
transition-duration: 0.3s;
transition-timing-function: ease;
transition-delay: 0s;
}
In practice almost everyone uses the transition shorthand, which takes the values in the order property, duration, timing-function, delay:
.button {
transition: background-color 0.3s ease 0s;
}
Three facts beginners must know:
- The default duration is
0s. If you write transition: background-color; and forget the duration, the change still happens instantly and you will see nothing. The duration is the part that actually creates the motion.
- To animate several properties, list them separated by commas:
transition: color 0.2s ease, transform 0.3s ease;. Each property can even have its own duration and delay.
transition: all; animates every changing property, which is convenient but wasteful and can produce surprise movements. Prefer naming exactly the properties you want.
Also note that only animatable values transition smoothly: colors, lengths, opacity, transform, shadows and similar numeric or color values. Properties such as display have no in-between values, so they jump instantly no matter what you do.
5. How a transition works, step by step
Follow the button example through the browser's eyes:
- The browser renders the button with its base styles:
background-color: #2563eb. The transition declaration is recorded, but nothing moves yet — a transition sitting idle does nothing.
- The user moves the cursor over the button. The
:hover rule now applies, asking for background-color: #1d4ed8.
- The browser notices that
background-color is listed in transition-property with a duration of 0.3s. Instead of applying the new color in one frame, it computes many intermediate colors, frame by frame, across 0.3 seconds.
- Each intermediate frame follows the timing function, so the color may change quickly at first and settle gently at the end.
- When the duration is over, the button shows exactly the hover color.
- The user moves the cursor away. The hover rule stops applying, so the value returns to the base color — and because the
transition declaration lives on the base state, the return journey is animated too.
This last point is why the transition belongs in the base rule, not inside :hover. If you declare it only in the hover rule, the change animates on the way in but snaps back instantly on the way out.
6. Timing functions: shaping the speed of change
The timing function, also called easing, decides how the value travels through time. Two changes can both take 0.3 seconds and still feel completely different: one can rush out of the gate and glide to a stop, the other can creep forward and then accelerate. CSS offers five keywords plus two ways to build custom curves.
| Keyword | Shape of the motion | Typical use |
ease | Starts fast, slows toward the end (this is the default) | General interface changes |
linear | Exactly the same speed from start to end | Spinners, loops, progress movement |
ease-in | Slow start, fast finish | Things leaving the screen |
ease-out | Fast start, gentle finish | Things arriving on screen |
ease-in-out | Slow at both ends, faster in the middle | Back-and-forth or repeating movement |
For full control, cubic-bezier(x1, y1, x2, y2) defines a custom curve. The keyword ease is actually shorthand for cubic-bezier(0.25, 0.1, 0.25, 1). The x values must stay between 0 and 1, but the y values may go outside that range, which produces an overshoot — the element briefly travels past its target and settles back, a lively effect for drawers and pop-ups:
.drawer {
transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55);
}
There is also steps(n), which skips interpolation entirely and jumps between values in n discrete steps. It is used for deliberately choppy effects, such as a clock hand that ticks rather than glides:
.clock-hand {
animation: rotate 60s steps(60) infinite;
}
7. Worked examples with transitions
A complete button example
Here is a full, runnable page so you can see every piece in place:
<!DOCTYPE html>
<html>
<head>
<style>
.button {
background-color: #2563eb;
color: #ffffff;
border: none;
border-radius: 6px;
padding: 10px 20px;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #1d4ed8;
}
</style>
</head>
<body>
<button class="button">Save changes</button>
</body>
</html>
Open the file in a browser and hover the button. Without the transition line the color would switch in a single frame; with it, the browser paints a smooth blend over 0.3 seconds. Delete the line and reload to feel the difference — this two-line experiment is the fastest way to understand what transitions add.
A card that lifts on hover
A common pattern on dashboards and product grids: the card rises slightly and its shadow deepens, suggesting it can be clicked.
.card {
background-color: #ffffff;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.25s ease-out, box-shadow 0.25s ease-out;
}
.card:hover {
transform: translateY(-6px);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.18);
}
Two properties are animated at once, each named explicitly. The lift uses transform: translateY() rather than changing any layout property, which keeps the motion smooth — the reason for this is explained in the final section.
An underline that grows from the left
Navigation links often reveal a small underline on hover. The trick is a pseudo-element whose horizontal scale goes from 0 to 1:
.nav-link {
position: relative;
text-decoration: none;
color: #111827;
}
.nav-link::after {
content: "";
position: absolute;
left: 0;
bottom: -4px;
width: 100%;
height: 2px;
background-color: #2563eb;
transform: scaleX(0);
transform-origin: left;
transition: transform 0.3s ease;
}
.nav-link:hover::after {
transform: scaleX(1);
}
The ::after pseudo-element is a thin bar attached to the link. It starts squashed to zero width with scaleX(0) and stretches to full width on hover. transform-origin: left makes it grow from the left edge; change it to right and the same bar will grow from the right instead.
A staggered reveal driven by one class
Menus and lists often appear item by item. The CSS gives every item the same transition but a different delay, and all JavaScript has to do is toggle one class:
.menu-item {
opacity: 0;
transform: translateY(10px);
transition: opacity 0.4s ease, transform 0.4s ease;
}
.menu-item:nth-child(1) { transition-delay: 0s; }
.menu-item:nth-child(2) { transition-delay: 0.1s; }
.menu-item:nth-child(3) { transition-delay: 0.2s; }
.menu-item.is-visible {
opacity: 1;
transform: translateY(0);
}
When is-visible is added, the three items fade and rise one after another like a wave. One small caveat: the delays also apply when the class is removed, so the items also disappear in a stagger. If you want a one-way stagger, override transition-delay: 0s; inside the visible state.
8. Keyframe animations: the @keyframes rule
Transitions only know a start value and an end value. When you need middle stops — or motion that runs without any trigger — you write a @keyframes rule. It has a name of your choosing and a set of stops, each describing the element's styles at that moment:
@keyframes grow {
from {
transform: scale(0.5);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
from and to are shorthand for 0% and 100%. For anything more interesting, use percentage stops, which may list several properties and need not cover every property at every stop:
@keyframes color-cycle {
0% { background-color: #ef4444; }
50% { background-color: #f59e0b; }
100% { background-color: #22c55e; }
}
Rules worth remembering:
- The name must be one word (letters, digits, hyphens, underscores) and is case-sensitive:
slide-in and Slide-In are different animations.
- A keyframe rule only defines the sequence. Nothing plays until some element references the name through its
animation properties.
- If a stop omits a property, the browser interpolates that property between the stops where it does appear.
9. The animation properties and their shorthand
Attaching an animation to an element involves eight controls, each available as a longhand property:
| Property | What it controls | Example value |
animation-name | Which @keyframes rule to play | slide-in |
animation-duration | How long one cycle lasts | 0.6s |
animation-timing-function | Speed curve applied within each cycle | ease-out |
animation-delay | Wait before the animation starts | 0.3s |
animation-iteration-count | How many cycles to play | 2 or infinite |
animation-direction | Play order of cycles: normal, reverse, alternate, alternate-reverse | alternate |
animation-fill-mode | Styles before the start and after the end: none, forwards, backwards, both | both |
animation-play-state | Whether it is running or paused | paused |
The animation shorthand packs these together. The one trap is that the first time value is always the duration and the second is the delay:
.banner {
animation: slide-in 0.6s ease-out 0.3s 2 normal both;
}
Reading the values in order: play slide-in, each cycle lasts 0.6s, easing ease-out, wait 0.3s before starting, play 2 cycles, direction normal, fill mode both.
The fill mode deserves a slow explanation, because it fixes the most common animation complaint ("my element snaps back when the animation ends"):
none — before and after the animation, the element shows its ordinary styles, so it visibly jumps at both ends.
forwards — after finishing, the element keeps the final keyframe's styles.
backwards — during the delay period, the element already shows the first keyframe's styles.
both — forwards and backwards together, the safest choice for entrance effects.
10. How a keyframe animation runs, step by step
- You write a
@keyframes rule. The browser stores the sequence but plays nothing — a keyframe rule on its own is inert.
- You attach the name through
animation-name or the animation shorthand on a selector.
- When an element starts matching that selector — the page loaded, or a class was added — the animation begins, after honoring any delay. During a delay with
backwards or both fill mode, the element already wears the first keyframe's styles.
- The browser interpolates every property between consecutive stops, following the timing function. With percentage stops, the curve is applied separately to each segment between stops.
- When one cycle ends, the iteration count decides whether to repeat, and the direction decides whether the next cycle runs forward, backward, or alternates.
- After the final cycle, the fill mode decides which styles remain. With
none, the element returns to its normal styles; with forwards or both, it holds the last keyframe.
- At any moment,
animation-play-state can pause the animation and later resume it from the same point — useful for effects that freeze while a user is reading.
11. Worked examples with keyframe animations
A loading spinner
The classic endless rotation. Notice that only a to stop is needed — the starting point is simply the element's own style:
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #e5e7eb;
border-top-color: #2563eb;
border-radius: 50%;
animation: spin 0.9s linear infinite;
}
The element is a circle with a mostly light border and one dark segment; rotating it forever produces the familiar loader. The timing function is linear because a spinner must not visibly speed up and slow down.
A pulsing "live" indicator
A small dot that breathes to show something is active. The first and last stops are written together because they share the same styles:
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.15);
}
}
.live-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #22c55e;
animation: pulse 1.2s ease-in-out infinite;
}
ease-in-out makes each swell grow gently and shrink gently, which reads as "breathing". With linear the same animation would look robotic.
A notice that slides in — with fill mode done right
@keyframes slide-in {
from {
opacity: 0;
transform: translateX(-40px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.notice {
animation: slide-in 0.6s ease-out 0.3s both;
}
Walk through what both achieves here. The animation has a 0.3 second delay; during that delay, backwards keeps the notice invisible and shifted left, so the user never sees it sitting in the wrong place. After the animation finishes, forwards holds the final styles. Remove the fill mode and the notice would be fully visible during the delay, then jump to invisible and slide in — a jarring flicker that beginners meet constantly.
A multi-stop attention bounce
Percentage stops let you choreograph several movements inside one cycle. This "scroll down" hint bounces high, then gives a smaller second hop:
@keyframes bounce {
0% { transform: translateY(0); }
30% { transform: translateY(-12px); }
50% { transform: translateY(0); }
70% { transform: translateY(-6px); }
100% { transform: translateY(0); }
}
.scroll-hint {
animation: bounce 1.6s ease-in-out infinite;
}
A transition could never express this, because there are five stops, not two. This is exactly the kind of effect that tells you "this one is an animation, not a transition".
12. Transitions versus animations: choosing the right tool
| Aspect | Transition | Animation |
| Trigger | Needs a state change: hover, focus, a toggled class | Can start by itself as soon as it is applied |
| Stops along the way | Only a start value and an end value | Any number of percentage keyframes |
| Looping | Not supported | infinite and any count |
| Reversing | Reverses automatically when the state ends | Needs animation-direction or a second animation |
| Pause and resume | No | Yes, via animation-play-state |
| Typical jobs | Hover and focus feedback, showing and hiding, small state changes | Loaders, entrance effects, attention seekers, looping decoration |
A simple decision rule: if the motion is a response to a state change between exactly two looks, use a transition. If the motion must happen unprompted, repeat, pause, or pass through intermediate poses, use a keyframe animation. When in doubt, start with a transition — it is shorter, and it reverses for free.
13. Performance and good habits for smooth motion
Not all animated properties cost the same. Changing things like width, height, padding, margin, top or left forces the browser to recompute the page layout on every single frame, which can stutter on long or complex pages. Two properties are dramatically cheaper:
transform moves, scales and rotates an element after layout, without disturbing anything around it.
opacity changes transparency without touching layout either.
So slide elements with translateX() and translateY() instead of left and top, and fade them with opacity. Nearly every example in this page follows that rule deliberately.
Respect users who ask for less motion. Operating systems offer a "reduce motion" setting, and CSS can read it with a media query — a habit that costs little and matters to many users:
@media (prefers-reduced-motion: reduce) {
.live-dot,
.scroll-hint,
.spinner {
animation: none;
}
.card,
.button {
transition: none;
}
}
Finally, a checklist of the mistakes this page has already warned about, worth revising before any project:
- Writing a
transition without a duration — the default 0s makes it invisible.
- Declaring the transition only inside
:hover, so the way back snaps instead of animating.
- Trying to transition
display, which has no intermediate values and always jumps.
- Animating layout properties on large elements instead of
transform and opacity.
- Forgetting
animation-fill-mode, so entrance animations end with an ugly snap back to the starting look.
- Running many infinite animations at once, which distracts users and burns battery.
14. Real-world patterns: motion on real interfaces
Part 1 built the mechanics; this part uses them the way production interfaces do. Three patterns appear on almost every modern site: an overlay that fades, a tooltip that waits, and a skeleton that shimmers while data loads.
An overlay and dialog that fade and settle
The classic problem: you cannot transition display, so how does a hidden modal fade in? The standard answer is to hide it with opacity and visibility instead. visibility is a special case: when it takes part in a transition, it becomes visible immediately on the way in and only flips to hidden at the very end of the way out — exactly the behaviour a fade needs.
.overlay {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(15, 23, 42, 0.5);
opacity: 0;
visibility: hidden;
transition: opacity 0.25s ease, visibility 0.25s;
}
.overlay.is-open {
opacity: 1;
visibility: visible;
}
.dialog {
background-color: #ffffff;
border-radius: 10px;
padding: 24px;
transform: scale(0.95) translateY(12px);
transition: transform 0.25s ease-out;
}
.overlay.is-open .dialog {
transform: scale(1) translateY(0);
}
JavaScript — or React, later in this course — only adds or removes the is-open class. The dimming layer fades, and the dialog rises a few pixels while scaling up, which reads as "coming toward you".
A tooltip that waits before appearing
If a tooltip appeared the instant the cursor grazed a button, it would flash constantly while the pointer crosses a toolbar. The fix is a short delay on the way in — plus a subtlety worth memorising: the browser takes the transition values from the state being entered. So the base rule gets a fast, delay-free transition (snappy disappearance) and the hover rule gets the delayed one (patient appearance).
.tip-host { position: relative; }
.tooltip {
position: absolute;
bottom: calc(100% + 8px);
left: 50%;
transform: translateX(-50%) translateY(4px);
background-color: #111827;
color: #ffffff;
font-size: 13px;
padding: 6px 10px;
border-radius: 6px;
white-space: nowrap;
opacity: 0;
pointer-events: none;
transition: opacity 0.15s ease, transform 0.15s ease;
}
.tip-host:hover .tooltip {
opacity: 1;
transform: translateX(-50%) translateY(0);
transition: opacity 0.15s ease 0.4s, transform 0.15s ease 0.4s;
}
Note pointer-events: none: an invisible element still catches the cursor, and a tooltip sitting above its host would otherwise steal the very hover that shows it.
A skeleton shimmer while content loads
Instead of a spinner, modern interfaces often show grey blocks shaped like the coming content, with a soft light band sweeping across them:
@keyframes shimmer {
from { background-position: 200% 0; }
to { background-position: -200% 0; }
}
.skeleton {
background-color: #e5e7eb;
background-image: linear-gradient(90deg, #e5e7eb 25%, #f3f4f6 50%, #e5e7eb 75%);
background-size: 200% 100%;
border-radius: 4px;
animation: shimmer 1.4s linear infinite;
}
The plain background-color underneath the moving gradient guarantees the sweep never exposes an empty edge. Stack a few .skeleton blocks sized like a heading, an avatar and two text lines, and you have the familiar loading state of feed-style applications.
15. Running and coordinating several animations
One element can play several animations at once — list them separated by commas in the shorthand, giving each group its own complete values:
.badge {
animation:
pop-in 0.4s ease-out both,
glow 2s ease-in-out 0.5s infinite;
}
Here pop-in plays once on arrival and glow starts half a second later and loops forever. Sequencing several elements uses animation-delay the same way the staggered menu in Part 1 used transition-delay:
.stat { animation: rise 0.5s ease-out both; }
.stat:nth-child(1) { animation-delay: 0.05s; }
.stat:nth-child(2) { animation-delay: 0.15s; }
.stat:nth-child(3) { animation-delay: 0.25s; }
With both as the fill mode, every item waits invisibly in its "from" pose during its delay, then rises in turn. This one pattern — entrance animation plus stepped delays — covers dashboard cards, pricing columns, list rows and hero text lines.
16. Finding problems: how to debug CSS motion
- Every major browser's developer tools include an animations inspector that lets you pause, replay and slow an animation down — the fastest way to see where a keyframe goes wrong.
- If nothing plays at all, check four things: the keyframe name is spelled identically in both places, the selector really matches the element, the duration is not
0s, and the element is not hidden with display: none. A misspelled name produces silence, not an error message.
- If it plays but looks wrong, temporarily animate something unmistakable — a solid
background-color — to confirm the timeline itself, then restore the real property.
- If a transition works in one direction only, revisit the rule from Part 1: the transition declaration must be visible to both states involved.
17. Common mistakes and the correct way
Animating height from auto
An expandable menu wants to grow from height: 0 to height: auto — but auto is not a number, so there is nothing to interpolate and the menu snaps open.
/* snaps: auto cannot be interpolated */
.menu { height: 0; overflow: hidden; transition: height 0.3s ease; }
.menu.is-open { height: auto; }
/* works: two real numbers to travel between */
.menu { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; }
.menu.is-open { max-height: 20rem; }
The max-height fix has one trade-off: if the value far exceeds the content, the visible motion finishes early and feels rushed, so pick a value close to the real content height. A modern alternative animates grid-template-rows from 0fr to 1fr, which tracks the content exactly.
Writing the delay before the duration
In the animation shorthand the first time value is always the duration and the second is the delay, whatever you intended:
/* meant: 0.5s animation after a 2s wait — actually 2s long, 0.5s late */
.badge { animation: pop 2s 0.5s ease both; }
/* correct */
.badge { animation: pop 0.5s ease 2s both; }
Leaving an invisible element clickable
opacity: 0 changes only appearance. The element still occupies space and receives clicks, so a hidden panel can silently block buttons underneath. Either give it pointer-events: none while hidden, or hide it with visibility as the overlay example did — hidden elements do not respond to the pointer.
Re-adding a class to restart an animation
Adding a class the element already has changes nothing, so the animation does not replay:
// second click appears to do nothing
box.classList.add("shake");
// remove first, force the browser to notice, then add again
box.classList.remove("shake");
void box.offsetWidth;
box.classList.add("shake");
The odd-looking void box.offsetWidth; reads a layout property, which forces the browser to apply the pending removal immediately; without that step, the removal and the re-add merge into one no-op change.
Transitioning box-shadow on many cards
Shadows are expensive to repaint, and a grid of cards each blending its shadow every frame can stutter. The optimised pattern paints the big shadow once on a pseudo-element and fades its opacity:
.card { position: relative; transition: transform 0.25s ease-out; }
.card::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
box-shadow: 0 12px 24px rgba(15, 23, 42, 0.18);
opacity: 0;
transition: opacity 0.25s ease-out;
}
.card:hover { transform: translateY(-6px); }
.card:hover::after { opacity: 1; }
18. Best practices for motion in real projects
- Keep durations in a sensible band: roughly 150–250 ms for hover and focus feedback, 200–300 ms for things appearing or disappearing, up to about 400 ms for large surfaces like modals and drawers. Looping indicators can run longer, but with
linear timing so they feel calm.
- Reuse a small set of durations and easings across the whole interface. Consistent motion is part of visual consistency; six different easings on one page feel broken even when each is fine alone.
- Motion must carry information — entrance, feedback or emphasis. If you cannot say in one sentence what a movement communicates, remove it.
- Never animate what the user is trying to read. Keep paragraphs and large text blocks still; reserve motion for controls, indicators and containers.
- Name keyframes after the effect (
fade-up, pop-in), never anim1, and comment timelines whose percentage stops are not self-explanatory.
- Prefer
transform and opacity, Part 1's rule, and reach for will-change only on the few elements that genuinely stutter — it is a hint with a memory cost, not a general accelerator.
- Test with the keyboard: focus states deserve the same transition care as hover states, and many users never touch the mouse.
- Treat motion as enhancement: every message must remain readable if the animation never runs.
19. Practical project: an animated sign-in card
Everything from both parts in one small build: an entrance animation, focus transitions, button feedback and a loading state driven by a single class.
Step 1: the static structure
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign in</title>
<style>
/* styles from steps 2 and 3 go here */
</style>
</head>
<body>
<main class="scene">
<form class="card">
<h2 class="card-title">Welcome back</h2>
<label class="field">
<span>Email</span>
<input type="email" placeholder="[email protected]">
</label>
<label class="field">
<span>Password</span>
<input type="password" placeholder="********">
</label>
<button class="submit" id="submit" type="button">
<span class="label">Sign in</span>
<span class="spinner"></span>
</button>
</form>
</main>
<script>
/* script from step 4 goes here */
</script>
</body>
</html>
Step 2: entrance, focus and button feedback
.scene {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: #f1f5f9;
}
@keyframes card-in {
from { opacity: 0; transform: translateY(24px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.card {
width: 320px;
background-color: #ffffff;
border-radius: 12px;
padding: 28px;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.12);
animation: card-in 0.5s ease-out 0.2s both;
}
.field { display: block; margin-bottom: 16px; }
.field span { display: block; font-size: 14px; margin-bottom: 6px; }
.field input {
width: 100%;
padding: 10px 12px;
border: 1px solid #cbd5e1;
border-radius: 8px;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.field input:focus {
outline: none;
border-color: #2563eb;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}
.submit {
position: relative;
width: 100%;
padding: 12px;
border: none;
border-radius: 8px;
background-color: #2563eb;
color: #ffffff;
cursor: pointer;
transition: background-color 0.2s ease, transform 0.1s ease;
}
.submit:hover { background-color: #1d4ed8; }
.submit:active { transform: scale(0.98); }
Reload: the card rises into place (the 0.2s delay with fill mode both keeps it invisible until the animation starts), the inputs glow softly when focused — by mouse or by the Tab key — and the button darkens on hover and dips slightly while pressed.
Step 3: the loading state
.label { transition: opacity 0.2s ease; }
.spinner {
position: absolute;
top: 50%;
left: 50%;
width: 18px;
height: 18px;
margin: -9px 0 0 -9px;
border: 2px solid rgba(255, 255, 255, 0.4);
border-top-color: #ffffff;
border-radius: 50%;
opacity: 0;
transition: opacity 0.2s ease;
}
@keyframes spin { to { transform: rotate(360deg); } }
.submit.is-loading { pointer-events: none; }
.submit.is-loading .label { opacity: 0; }
.submit.is-loading .spinner {
opacity: 1;
animation: spin 0.8s linear infinite;
}
The is-loading class fades the text out, fades the ring in and sets it spinning; pointer-events: none blocks double clicks while the request is "in flight". The CSS never knows when loading ends — the class simply gets removed.
Step 4: toggling the class with a few lines of JavaScript
const button = document.getElementById("submit");
button.addEventListener("click", function () {
button.classList.add("is-loading");
setTimeout(function () {
button.classList.remove("is-loading");
}, 2000);
});
The setTimeout stands in for a real server call: in a working application you would remove the class when the response arrives. Notice the division of labour, because it is the same division you will use throughout React: JavaScript changes state by toggling a class; CSS owns every frame of the motion. Events are taught properly later in this course — for now, read the script as "when clicked, add the class; after two seconds, remove it".
Step 5: test it
- Reload and watch the entrance animation.
- Press Tab twice — both inputs must show the focus ring without the mouse.
- Hover and press the button; confirm the darken and dip effects.
- Click the button: the label fades out, the ring spins, further clicks are blocked, and after two seconds everything returns.
20. Practice Exercises
- Modify the growing underline from Part 1 so it retracts toward the right on mouse-out (hint:
transform-origin).
- Build a toggle switch: a track and a knob that slides with
translateX(), plus a track colour change, all with one transition.
- Create a "typing" loader of three dots that pulse one after another, sharing one keyframe rule and using stepped
animation-delay values.
- Animate a progress bar from empty to full with
transform: scaleX() and transform-origin: left — deliberately not width.
- Give a card two simultaneous animations: a one-time entrance and an infinite gentle float using
animation-direction: alternate.
- Build a two-sided card that flips on hover with
rotateY(180deg), keeping the back face hidden until it turns.
- Add a
prefers-reduced-motion block that disables every animation and transition from exercises 1 to 6.
- Extend the sign-in project so the two fields fade in after the card, each with its own delay, reusing the card's entrance keyframes.
21. Interview Questions and Answers
What is the difference between a transition and an animation?
A transition needs a state change — hover, focus, a toggled class — and blends between exactly two values. A @keyframes animation runs on its own once applied, supports any number of intermediate stops, can loop and can be paused. Rule of thumb: reactions use transitions, performances use animations.
Why can some properties not be transitioned?
A transition computes intermediate values between two endpoints. Colours, lengths, opacity and transform have meaningful in-between values; display does not — an element is either displayed or not, so it jumps. The usual workaround is hiding with opacity plus visibility, as the overlay example showed.
What does animation-fill-mode: both do?
It applies the first keyframe's styles during the delay period and holds the last keyframe's styles after the animation finishes. Without it, a delayed entrance shows the element in its normal styles first, then snaps it to the start pose — the flicker that both prevents.
How are duration and delay told apart in the animation shorthand?
By order: the first time value is the duration, the second is the delay. Other values such as name, easing, count and fill mode are matched by type, but the two time values are order-dependent, so animation: pop 2s 0.5s; means a 2-second animation delayed by 0.5 seconds.
What is a timing function and what does cubic-bezier() do?
It is the speed curve of the change. Keywords like ease-out are predefined curves; cubic-bezier(x1, y1, x2, y2) defines a custom one, and y values outside the 0–1 range create overshoot, where the element briefly passes its target and settles back.
Why do developers animate transform and opacity rather than width, height or top?
Layout properties force the browser to recompute the position of everything around the element on every frame. transform and opacity apply after layout, so the browser can usually hand the work to the compositor and hold the full frame rate.
How do you pause and resume a CSS animation?
With animation-play-state: paused, and back to running to resume from the same point — typically toggled by adding and removing a class.
How do you run two animations on one element?
Comma-separate them in the shorthand, giving each group its own values, for example animation: pop-in 0.4s ease-out both, glow 2s linear 0.5s infinite;.
How do you restart a CSS animation from JavaScript?
Remove the class that applies it, force the browser to register the removal — the classic trick is reading element.offsetWidth — then add the class again. Simply re-adding a class that is already present changes nothing.
What is the difference between animation-direction: alternate and reverse?
reverse plays every cycle backwards. alternate plays the first cycle forward, the second backward, and so on, producing a natural back-and-forth loop without writing a second keyframe rule.
What is will-change and when should you use it?
It is a hint telling the browser that a given property will change, so optimisations can be prepared in advance. Use it sparingly, just before a demanding animation on a specific element, and remove it afterwards — applied everywhere, it wastes memory and can slow pages down.
What is steps() used for?
It disables smooth interpolation and jumps between values in a fixed number of discrete steps, for deliberately choppy effects such as a ticking clock hand or sprite-style movement.
22. Quick Revision Checklist
- I can explain the difference between a transition and a keyframe animation in one sentence each.
- I know the four longhands behind
transition and that duration defaults to 0s.
- I know the eight longhands behind
animation and that the first time value is the duration, the second the delay.
- I can write a
@keyframes rule with percentage stops and attach it with the right fill mode.
- I can explain
forwards, backwards and both using the delayed-notice example.
- I can name the five easing keywords and build an overshoot with
cubic-bezier().
- I know why
transform and opacity are the cheap properties to animate.
- I can hide and reveal an element smoothly with
opacity plus visibility.
- I can stagger items with stepped delays and run two animations on one element.
- I can restart an animation from JavaScript and know why re-adding the same class fails.
- I check my motion against
prefers-reduced-motion before calling a build finished.
23. Official Documentation and Further Reading
No CSS specification pages were confirmed by this course's research, so the reading list stays within the course's approved resources. They sit in the React track you are moving toward, and each connects to the ground just covered:
Conclusion
CSS motion is two ideas and a great deal of judgement. Transitions blend a change that a state shift already causes; keyframe animations perform a timed sequence on their own; everything else — easing, delay, fill mode, staggering, the transform-and-opacity rule — exists to make those two ideas feel deliberate. With this sub-module, the motion work of the CSS3 & Responsive Design module is complete, and the pattern that matters most going forward is the one from the sign-in project: JavaScript and React will decide when state changes, and CSS will decide how that change looks while it happens. Keep the durations short, the easings consistent, the loops calm, and every animation optional for users who ask for less.
Learn more in the React JS Training course, or register for a course demo.