Sub topic 11
Keeping motion smooth: transform, opacity and layout cost
This chapter assumes you can write a transition and a @keyframes animation, and that you know the cascade and basic selectors. It explains why two animations that look the same in code can feel very different on a phone. It also shows how to choose properties that keep motion at a steady frame rate.
What "smooth" means
A display refreshes at a fixed rate, usually 60 times per second. The browser has about 16.7 milliseconds to produce each frame. On a 120 Hz display the budget is about 8.3 milliseconds. If a frame takes longer, the browser skips it, and the motion appears to stutter. Developers call this jank.
Producing a frame means running several steps. Some steps are cheap and some are expensive. Which steps your animation forces the browser to repeat decides whether it stays inside the budget.
The rendering pipeline
When a style value changes, the browser may need to run some or all of these stages:
- Style: work out which rules apply to each element.
- Layout: compute the size and position of every affected box.
- Paint: draw pixels for text, colors, borders and shadows into layers.
- Composite: combine the painted layers into the final image, usually on the GPU.
A change that starts at layout also repeats paint and composite. A change that starts at paint repeats composite. A change that only needs compositing skips the other stages. That is the whole performance model: pick properties that start as late in the pipeline as possible.
The three cost tiers
| Tier | Example properties | Work per frame | Typical cost |
|---|---|---|---|
| Layout | `width`, `height`, `top`, `left`, `margin`, `padding`, `font-size` | Layout, paint, composite | High. Can move other boxes. |
| Paint | `color`, `background-color`, `border-color`, `box-shadow`, `outline` | Paint, composite | Medium. Depends on the painted area. |
| Composite | `transform`, `opacity` | Composite only | Low. Often runs off the main thread. |
Exact behavior varies by browser and by element. A small paint on a small element can be cheap, and a layout change on an isolated element can also be cheap. Treat the table as a default ordering. Confirm with measurement, as described later in this chapter.
Why transform and opacity are cheap
The browser can promote an element that is animating transform or opacity to its own compositor layer. It paints that layer once as a texture. After that, the compositor thread can move, scale, rotate or fade the texture on the GPU without asking the main thread to run layout or paint again.
This has a visible consequence. If JavaScript is busy for 100 milliseconds, a transform animation running on the compositor can keep going, while a left animation freezes because it needs the main thread on every frame.
Moving a box with left forces layout:
.slider-slow {
position: relative;
left: 0;
transition: left 300ms ease-out;
}
.slider-slow.open {
left: 200px;
}Moving it with transform produces the same visual result without layout:
.slider-fast {
transition: transform 300ms ease-out;
}
.slider-fast.open {
transform: translateX(200px);
}One difference matters. transform does not change the layout box. Neighbouring elements do not move, and the element's original space stays reserved. This is usually what you want for motion effects, but it means you cannot use transform to make surrounding content reflow.
Replacing expensive properties
Most expensive animations can be rewritten. These patterns cover the common cases.
Size changes: use scale
Instead of animating width and height on a decorative element, animate transform: scale(). Scaling stretches the element's content, so it suits shapes, images and backgrounds. It distorts text and rounded corners, so it is a poor fit for a panel whose contents must stay readable.
Shadows: fade a pseudo-element
Animating box-shadow repaints the shadow on each frame. Paint the final shadow once on a pseudo-element, then animate its opacity:
.card {
position: relative;
transition: transform 200ms ease-out;
}
.card::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
box-shadow: 0 12px 24px rgb(0 0 0 / 0.25);
opacity: 0;
transition: opacity 200ms ease-out;
pointer-events: none;
z-index: -1;
}
.card:hover,
.card:focus-within {
transform: translateY(-4px);
}
.card:hover::after,
.card:focus-within::after {
opacity: 1;
}The z-index: -1 places the shadow behind the card content. It stays within the card's stacking context only if the card creates one. Here the card's transform on hover does that. Add isolation: isolate to .card if the shadow ever appears behind the page background in the resting state.
Color changes: crossfade with opacity
A background-color transition repaints. If the surface is large, stack two layers and fade the top one. For a small button the paint cost is usually negligible, so do not complicate it.
Collapsing panels
Animating height from 0 to auto is not possible directly, and animating a fixed height triggers layout on every frame. Layout cost is unavoidable if surrounding content must reflow. In that case, keep the animated subtree small and short. If the content does not need to push other content, slide it with transform and fade it with opacity instead.
Promoting layers with will-change
will-change tells the browser which property you are about to animate, so it can prepare a layer ahead of time:
.menu {
transform: translateX(-100%);
transition: transform 250ms ease-out;
}
.menu.is-opening {
will-change: transform;
}
.menu.open {
transform: translateX(0);
}const menu = document.querySelector('.menu');
function openMenu() {
menu.classList.add('is-opening');
requestAnimationFrame(() => {
menu.classList.add('open');
});
}
menu.addEventListener('transitionend', (event) => {
if (event.propertyName === 'transform') {
menu.classList.remove('is-opening');
}
});The script adds the hint, waits one frame so the browser can prepare the layer, starts the motion, and removes the hint when the transition ends.
Side effects of transform and opacity
Using cheap properties changes more than speed. Watch for these:
- Stacking context: an element with
opacitybelow 1 or anytransformother thannonecreates a new stacking context. Az-indexon a child can no longer escape it, so a dropdown inside such an element may appear under a sibling. - Containing block: a
transformmakes the element the containing block forposition: fixeddescendants. A fixed header inside a transformed parent scrolls with that parent. - Blurry text: scaling or fractional translation can leave text blurry while the layer is composited. It usually sharpens when the animation ends. Prefer whole-pixel translations for text-heavy content.
- Hit testing: a transformed element's clickable area moves with it, while its layout box does not. Rapid hover animations can make a button move out from under the pointer and flicker between states. Put the hover on a stationary wrapper if this happens.
Common errors
- Animating
topandlefton aposition: absoluteelement because it worked in an older tutorial. Usetranslatevalues. - Transitioning
all. Any property that changes later, including layout properties, will animate and may cost frames. List properties explicitly. - Animating
filter: blur()orbackdrop-filteron large areas. These are paint-heavy even when they run on the GPU. Test on a low-end device. - Starting a transition in the same frame that an element is inserted or restyled, then wondering why nothing animates. The browser needs a computed starting value first.
- Assuming that a smooth animation on a developer laptop is smooth everywhere. Test with CPU throttling.
Measuring instead of guessing
Open the Performance panel in your browser's developer tools, record while the animation runs, and look at the frame timeline. Long purple "Layout" or green "Paint" blocks in each frame show which stage is costing time. The Rendering panel also has an option to flash paint areas, which highlights regions that are repainted on every frame. Use CPU throttling to expose problems that a fast machine hides.
Exercise
A sidebar slides in by transitioning left from -300px to 0. The slide stutters while a heavy script runs. Rewrite the CSS so the slide is compositor-friendly, and explain why it keeps running while the main thread is busy.
Show answer
Use .sidebar { transform: translateX(-300px); transition: transform 300ms ease-out; } and .sidebar.open { transform: translateX(0); }. Animating left changes layout, so every frame needs the main thread for layout, paint and composite. A transform animation can be promoted to its own layer, and the compositor thread moves that layer without layout or paint, so it continues even while JavaScript blocks the main thread.
Exercise
A card grows a large box-shadow on hover with transition: box-shadow 200ms. It repaints each frame. How can you avoid that, and what must the pseudo-element have so it does not block clicks?
Show answer
Paint the final shadow once on a ::after pseudo-element with opacity: 0, transition its opacity to 1 on hover, and set pointer-events: none on it so it does not intercept pointer events.