When you hover over a button and its colour changes, the change normally happens in a single frame: blue, then instantly dark blue. It works, but it feels mechanical. Real objects don't teleport between states, they move.
A CSS transition tells the browser: "when this property changes, don't jump; slide smoothly from the old value to the new one over some time." One line of CSS can turn a stiff interface into one that feels polished.
In this chapter we learn the four transition properties, how timing functions (easing) work with real numbers, which properties can and cannot be transitioned, why transform and opacity are the fastest things to animate, and modern tricks for animating height: auto and display: none.
What is a Transition?
A transition animates a CSS property from its old value to its new value over a period of time, whenever that property's computed value changes.
Three ingredients are needed:
Two states: a starting style and a changed style (for example normal and
:hover, or before and after JavaScript adds a class).Something that changes the state: hover, focus, a class being added, a media query becoming true, and so on.
A
transitiondeclaration saying which property to animate and for how long.
A transition never runs on its own. No state change, no transition. If you want something to move automatically when the page loads, or to loop forever, you need keyframe animations instead (see Animations & Keyframes).
Your First Transition
<button class="btn">Enroll now</button>.btn {
background-color: #2563eb;
color: white;
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: background-color 300ms ease;
}
.btn:hover {
background-color: #1e40af;
}Output: when the mouse moves onto the button, its background fades from bright blue to dark blue over 0.3 seconds. When the mouse leaves, it fades back over 0.3 seconds.
Notice where the transition is written: on the normal .btn rule, not on :hover. We'll see why that matters shortly.
The Four Transition Properties
| Property | What it controls | Default | Example |
|---|---|---|---|
transition-property | Which property (or properties) to animate | all | background-color |
transition-duration | How long one transition takes | 0s | 300ms or 0.3s |
transition-timing-function | The speed curve (easing) | ease | ease-out |
transition-delay | Waiting time before it starts | 0s | 100ms |
Since the default duration is 0s, nothing visible happens until you give a duration. That's why transition-property: background-color; alone appears to do nothing.
Written in long form, our button transition is:
.btn {
transition-property: background-color;
transition-duration: 300ms;
transition-timing-function: ease;
transition-delay: 0s;
}The shorthand
In practice everyone uses the transition shorthand:
/* property | duration | timing-function | delay */
transition: background-color 0.3s ease 0.1s;The order of the keywords is flexible, with one important rule:
In the
transitionshorthand, the first time value is always the duration and the second time value is always the delay.
So transition: opacity 1s 2s means "take 1 second, after waiting 2 seconds". Swap the numbers and you get a very different result.
Units of time
Durations and delays need a unit: s (seconds) or ms (milliseconds). 300ms = 0.3s. Writing a bare 300 is invalid, and the browser throws away the whole declaration.
Transitioning Several Properties
Separate each transition with a comma:
.btn {
transition: background-color 300ms ease,
transform 200ms ease-out;
}
.btn:hover {
background-color: #1e40af;
transform: translateY(-4px);
}Output: on hover the button darkens and rises 4 pixels. The colour change takes 300 ms, the lift takes 200 ms. (translateY() is covered properly in Transforms; for now, read it as "move up 4px".)
Each longhand property is also a comma-separated list, matched up by position:
transition-property: background-color, transform;
transition-duration: 300ms, 200ms;
transition-timing-function: ease, ease-out;Why not just transition: all?
transition: all 300ms is tempting, but it has real costs:
Every property that changes will animate, including ones you didn't plan for (a width changed by a media query, a colour changed by a theme switch...).
It can animate expensive properties like
widthortopby accident (see the performance section below).It makes the code harder to reason about: a reader can't tell what is meant to move.
List the properties you actually intend to animate. It's clearer and safer.
Where to Put the transition
This trips up almost every beginner. Compare these two versions:
/* Version A: transition on the base state */
.card { transition: transform 300ms; }
.card:hover { transform: scale(1.05); }
/* Version B: transition only on :hover */
.card:hover {
transform: scale(1.05);
transition: transform 300ms;
}Results:
| Mouse enters | Mouse leaves | |
|---|---|---|
| Version A | Smoothly grows | Smoothly shrinks |
| Version B | Smoothly grows | Snaps back instantly |
Why? The rule is:
The browser uses the
transitionvalue of the state the element is moving to.
When the mouse leaves in Version B, the element is moving to the normal .card state, which has no transition, so the change is instant.
You can use this rule on purpose to get different speeds in each direction:
.tooltip {
opacity: 0;
transition: opacity 600ms; /* used when hiding (slow fade-out) */
}
.has-tooltip:hover .tooltip {
opacity: 1;
transition: opacity 150ms; /* used when showing (quick fade-in) */
}Timing Functions (Easing)
The duration says how long; the timing function says how the speed is spread across that time.
A timing function maps time progress (0 to 1) to value progress (0 to 1). With linear, half the time means half the change. With the others, the change speeds up or slows down along the way.
| Keyword | Equivalent curve | Feels like | Value progress at 50% of the time |
|---|---|---|---|
linear | constant speed | Mechanical, robotic | 50% |
ease (default) | cubic-bezier(0.25, 0.1, 0.25, 1) | Quick start, gentle stop | ≈ 80% |
ease-in | cubic-bezier(0.42, 0, 1, 1) | Slow start, fast finish | ≈ 31.5% |
ease-out | cubic-bezier(0, 0, 0.58, 1) | Fast start, slow finish | ≈ 68.5% |
ease-in-out | cubic-bezier(0.42, 0, 0.58, 1) | Slow, fast, slow | 50% |
The last column was measured in Chrome by pausing a 1-second transition of width from 100px to 200px at 500 ms: ease gave 180.23px, ease-in gave 131.53px, ease-out gave 168.45px.
Here is how far each curve has got at each quarter of the time (calculated from each curve for a change from 0 to 100; Chrome gives the same values):
time progress: 25% 50% 75% 100%
linear 25.0 50.0 75.0 100
ease 40.9 80.2 96.0 100
ease-in 9.3 31.5 62.2 100
ease-out 37.8 68.5 90.6 100
ease-in-out 12.9 50.0 87.1 100Read the ease row: it covers 96% of the distance in the first three quarters of the time, then spends the last quarter creeping into place. That gentle landing is why it looks natural.
Which one should I use?
ease-outfor things entering or reacting to the user (menus opening, buttons responding). It responds instantly and settles gently, which feels snappy.ease-infor things leaving the screen (they accelerate away).ease-in-outfor things moving from one place to another on screen.linearmainly for colour/opacity fades or continuous motion like spinners.
cubic-bezier()
All the keyword curves are cubic Bézier curves from point (0, 0) to point (1, 1). You can define your own with two control points:
/* cubic-bezier(x1, y1, x2, y2) */
transition: transform 400ms cubic-bezier(0.34, 1.56, 0.64, 1);The x values must be between 0 and 1 (time can't go backwards), but the y values may go outside that range. A y value above 1 makes the value overshoot the target and come back, which gives a playful "bounce". Browser DevTools have a visual curve editor: click the small curve icon next to a timing function in the Styles panel.
steps()
steps(n) doesn't glide at all. It jumps in n equal steps, like a clock's second hand:
transition: width 400ms steps(4);For a width change from 100px to 200px over 400 ms with steps(4) (which means steps(4, end)), the value stays at each level for 100 ms and jumps at the end of each interval:
time: 0–99 ms 100–199 ms 200–299 ms 300–399 ms 400 ms
width: 100px 125px 150px 175px 200pxChecked in Chrome: at 150 ms the width is 125px, at 250 ms it is 150px. Steps are mostly used with keyframe animations (sprite sheets, typewriter effects), which we'll see in Animations & Keyframes.
linear() for custom curves
The linear() function (supported in all major browsers since late 2023) lets you list points that are joined by straight lines, for example linear(0, 0.25 75%, 1). With many points it can approximate springs and bounces that cubic-bezier() cannot. You'll usually generate it with an online tool rather than write it by hand.
Worked Example: Calculating a Transition by Hand
Questions like "what is the value at time t?" check whether you really understand delay and duration.
.bar {
width: 100px;
transition: width 300ms linear 100ms;
}
.bar.full {
width: 200px;
}The class full is added at time t = 0. What is the width at t = 150 ms?
From 0 to 100 ms the delay is running. The width stays
100px.The transition starts at 100 ms and ends at 100 + 300 = 400 ms.
At t = 150 ms we are 50 ms into a 300 ms transition, so time progress = 50 / 300 = 1/6.
With
linear, value progress = time progress = 1/6.Width = 100 + (200 − 100) × 1/6 ≈ 116.67px.
Chrome reports 116.656px at that moment, matching our calculation (the tiny difference is internal rounding).
Negative delays
A negative delay makes the transition start immediately, but as if it had already been running for that long. With transition: width 300ms linear -100ms, the bar jumps straight to one third of the way (≈ 133.33px) and finishes after the remaining 200 ms.
Which Properties Can Be Transitioned?
A property can transition smoothly only if the browser knows how to calculate values in between the start and end values. This is called interpolation.
| Animates smoothly | Does not animate smoothly |
|---|---|
Lengths and percentages: width, margin, padding, font-size, top... | display, position, float |
Colours: color, background-color, border-color | font-family, text-align, visibility* |
opacity, transform, box-shadow, filter | Keyword values such as height: auto (by default) |
Grid track sizes: grid-template-rows, grid-template-columns | Most properties whose values are keywords |
Properties in the right column are discrete: there is no "halfway between block and none". If you try to transition them, they simply flip from one value to the other (by default, instantly).
* visibility is special: it is not interpolated, but during a transition it stays visible for the whole duration whenever one end is visible. That's why the classic fade pattern transition: opacity 300ms, visibility 300ms works: the element stays visible while fading out and only becomes hidden (and unclickable) at the end.
Performance: Prefer transform and opacity
Every frame, the browser may need to do up to three kinds of work:
Layout ──► Paint ──► Composite
(where and (fill in the (stack the painted
how big?) pixels) layers together)Animating
width,height,margin,toporleftchanges geometry, so the browser must redo layout (and usually paint) on every frame, possibly for many other elements too.Animating
background-colororbox-shadowskips layout but needs repaint.Animating
transformandopacitycan usually be handled at the composite step alone, often on the GPU. These are the cheapest properties to animate and stay smooth even on slow phones.
So, to slide a panel in, transition transform: translateX(...) rather than left. To make a card grow on hover, use transform: scale(...) rather than width.
You may see will-change: transform; in some code. It hints to the browser that the property is about to change, so it can prepare a separate layer in advance. Use it only for elements that really animate and have a measured performance problem; adding it everywhere wastes memory.
The height: auto Problem
A very common wish: an accordion panel that smoothly opens to fit its content.
.panel { height: 0; overflow: hidden; transition: height 300ms; }
.panel.open { height: auto; } /* ❌ snaps open, no animation */The browser can't calculate "halfway between 0 and auto" because auto is a keyword, not a number, so the change is instant. There are three common solutions.
1. The max-height trick (old)
Transition max-height from 0 to a value "surely big enough", like 500px. It works, but the timing is wrong: if the content is only 100px tall and the timing is linear, the visible part of the animation finishes in the first fifth of the duration (100 / 500), and closing seems to start late.
2. The grid 0fr → 1fr trick (recommended today)
Grid track sizes can be transitioned in all major browsers, and a 1fr row in an auto-height grid is exactly as tall as its content:
<div class="panel">
<div class="panel-inner">
Panel content of any height...
</div>
</div>.panel {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 300ms ease;
}
.panel.open {
grid-template-rows: 1fr;
}
.panel-inner {
overflow: hidden; /* lets the row shrink below the content height */
}Output: a closed panel is 0px tall; an open panel grows smoothly to its natural content height (36px for two lines of 16px text in our test). The overflow: hidden on the inner element is essential: without it, the row cannot become smaller than the content. A grid item normally has an automatic minimum size equal to its content, so the 0fr row would be stretched to fit it; giving the item any overflow value other than visible sets that automatic minimum to 0.
3. interpolate-size (Chromium only for now)
Newer Chromium-based browsers (Chrome, Edge) support interpolate-size: allow-keywords;, which makes height: 0 → height: auto transition directly. Firefox and Safari don't support it yet, so treat it as an enhancement on top of a working fallback.
Fading In from display: none
Two more problems appear when an element appears or disappears:
When an element changes from
display: nonetodisplay: block, it has no "before" style, so nothing is transitioned: it just appears.When it changes to
display: none, it disappears immediately, cutting off any fade-out.
Modern CSS solves both:
.menu {
display: none;
opacity: 0;
transition: opacity 300ms ease,
display 300ms allow-discrete;
}
.menu.open {
display: block;
opacity: 1;
}
/* the style to start FROM the first time .menu.open is rendered */
@starting-style {
.menu.open {
opacity: 0;
}
}@starting-styledefines the "before" style for an element that is just being rendered (or just changed fromdisplay: none). It is Baseline newly available since August 2024.allow-discrete(thetransition-behaviorproperty, here inside the shorthand) allows a discrete property likedisplayto take part in a transition. When closing,displaystaysblockuntil the very end of the 300 ms, so the fade-out is visible, and then flips tonone.
We tested this in Chrome: halfway through closing, the menu still has display: block and opacity ≈ 0.2; after 300 ms it becomes display: none. Support note: @starting-style works in all major browsers, but Firefox does not yet support transitioning display itself. In Firefox the fade-in still works and the menu simply disappears without fading out, which is an acceptable fallback.
Transitions and JavaScript
Transitions are usually triggered by JavaScript adding or removing a class, which keeps the "how it looks" part in CSS:
const button = document.querySelector(".menu-button");
const menu = document.querySelector(".menu");
button.addEventListener("click", () => {
menu.classList.toggle("open");
});
menu.addEventListener("transitionend", (event) => {
console.log("Finished:", event.propertyName);
});When the menu finishes fading in, the console prints:
Finished: opacitytransitionend fires once per property that finished. If you transition three properties, you get three events, so check event.propertyName. It does not fire at all if the transition is cancelled (for example, the class is removed again halfway).
Interrupted transitions
If the user hovers and then leaves before the transition is complete, the browser doesn't finish the first one. It starts a new transition from the current in-between value back to the original. To avoid an odd, slow return over a tiny distance, the browser also shortens the reverse transition in proportion to how far the first one got.
Respecting Reduced Motion
Some users get dizzy or nauseous from on-screen motion and turn on "reduce motion" in their operating system. CSS can detect this setting:
@media (prefers-reduced-motion: reduce) {
.btn,
.panel,
.menu {
transition-duration: 0.01ms;
}
}Colour and opacity fades are generally fine. The things to tone down are large movements, zooms and parallax effects. A tiny duration like 0.01ms (instead of 0s) is a common choice so that transitionend events still fire for scripts that wait for them.
Common Mistakes
Forgetting the duration.
transition: background-color;has a duration of0s, so nothing animates.Missing units.
transition: opacity 300;is invalid. Write300ms.Putting the transition only on
:hover. Then the return trip snaps instantly.Swapping duration and delay. In the shorthand the first time is always the duration.
Transitioning to
height: autoand wondering why it snaps. Use the grid0fr→1frtrick.Animating layout properties (
left,width) whentransformwould do. It causes jank on low-end phones.Overusing
transition: all, which animates things you never intended.Very long durations. UI feedback should be quick: about 150–300 ms for small elements. Anything above about 500 ms starts to feel sluggish.
Interview / Exam Questions
1. What is the difference between a CSS transition and a CSS animation?
A transition animates between two states and runs only when a property value changes (hover, class change and so on). An animation uses @keyframes, can have many intermediate steps, can start by itself on page load, and can loop or alternate. Transitions are for "A to B on change"; animations are for anything more.
2. In transition: opacity 2s 1s, which is the duration and which is the delay?
The first time value (2s) is the duration and the second (1s) is the delay. The fade waits 1 second, then takes 2 seconds, finishing 3 seconds after the change.
3. Why does the hover effect animate in but snap back when the mouse leaves?
The transition was declared only inside the :hover rule. The browser uses the transition of the state being entered; when leaving hover, the normal state has no transition, so the change is instant. Move the transition to the base rule.
4. width transitions from 100px to 300px with transition: width 400ms linear 200ms. What is the width 300ms after the change?
The first 200 ms is delay, so at 300 ms the transition has run for 100 ms out of 400 ms (25%). Width = 100 + 200 × 0.25 = 150px.
5. Why are transform and opacity recommended for animations?
Changing them does not affect layout, and usually doesn't require repainting either. The browser can apply them at the compositing stage, often on the GPU, so they stay smooth at 60 frames per second. Properties like width or top force layout on every frame.
6. Can you transition display? How do you fade in an element that was display: none?
display is discrete, so it doesn't interpolate. In modern browsers you add display 300ms allow-discrete to the transition list, so the display change waits until the end when hiding, and use @starting-style to give the element an initial style (such as opacity: 0) to transition from when it first appears.
7. Which timing function is the default, and what does it look like?
ease, equal to cubic-bezier(0.25, 0.1, 0.25, 1). It starts fairly fast and slows down gently at the end; at half the time it has already covered about 80% of the change.
Summary
A transition smoothly animates a property when its value changes; it needs a state change to run.
Four properties:
transition-property,-duration(default0s),-timing-function(defaultease),-delay. In the shorthand, the first time is the duration, the second the delay.Put
transitionon the base state so it works in both directions; the target state's transition is the one used.Timing functions shape the speed:
ease-outfor entering,ease-infor leaving,steps()for jumps,cubic-bezier()/linear()for custom curves.Only interpolable properties animate smoothly; discrete ones like
displayflip.Prefer
transformandopacityfor smooth, cheap animations.Animate to content height with
grid-template-rows: 0fr→1fr; fade in fromdisplay: nonewith@starting-styleandallow-discrete.Respect
prefers-reduced-motion.
Next, in Transforms, we'll learn the property you'll transition most often: moving, rotating, scaling and skewing elements without disturbing the layout around them.