How do you prevent layout shift (CLS) in feeds and lazy-loaded images?
IntermediatePerformance interview questionBy UIRound, updated 23 November 2026
Short answer
Layout shift happens when something visible moves because content above or beside it changed size late. Prevent it by reserving the final space before content arrives: width and height on images, aspect-ratio on media and embeds, fixed slots for ads, and skeletons with the real size. In feeds, never insert content above what the user is reading unless they asked for it, and measure with layout-shift attribution in the field.
How CLS is scored
Each time a visible element changes its start position between two frames, the browser records a layout shift. Its score is:
layout shift score = impact fraction × distance fraction- Impact fraction: the share of the viewport covered by the moving elements, counting the area they covered before and after the move.
- Distance fraction: the largest distance any of them moved, divided by the viewport's larger dimension.
On a portrait phone screen, an element covering half the viewport that moves down by a quarter of the viewport height has an impact fraction of 0.75 and a distance fraction of 0.25, so the shift scores about 0.19. That one shift is already "poor" against the 0.1 target.
Three rules decide what counts:
- Only existing elements moving count. A new element appearing, or an element growing, is not a shift by itself. It becomes one when it pushes other visible content.
- Expected shifts are excluded. Shifts within 500 ms of a discrete input such as a click, tap or key press are flagged
hadRecentInputand ignored. Scrolling, dragging and pinch-zoom are not such inputs, so an image that pops in while the user scrolls does count. - Session windows. Shifts are grouped into windows: a window continues while shifts come less than 1 second apart, up to 5 seconds long. CLS is the score of the worst window over the whole life of the page, not just the load. A good CLS is 0.1 or less at the 75th percentile. The other Core Web Vitals are in what are LCP, INP and CLS.
Images: give the browser the box before the bytes
The most common cause is an image with no size. Until it loads it is zero pixels tall, then it expands and pushes everything below.
<img src="post-1280.avif" width="1280" height="960" loading="lazy" alt="Beach at sunset" />img {
max-width: 100%;
height: auto; /* the box scales, but keeps the 4:3 ratio from the attributes */
}Browsers turn the width and height attributes into a default aspect-ratio, so a responsive image still reserves the right height before a single byte arrives. You do not need the image to be displayed at 1280 pixels; the attributes only supply the ratio.
Lazy loading makes this more important, not less. A loading="lazy" image starts downloading as it nears the viewport, which is usually while the user is scrolling, and scroll is not an input that excuses the shift. How lazy loading works covers the loading side.
In a feed of user-uploaded media you do not know the dimensions when writing HTML. Record width and height when the file is uploaded, return them in the API, and render them:
function PostImage({ src, width, height, alt }) {
return (
<div className="media" style={{ aspectRatio: `${width} / ${height}` }}>
<img src={src} alt={alt} loading="lazy" />
</div>
);
}With img { width: 100%; height: 100%; object-fit: cover; } inside, the container's box is fixed and the image fills it. To force very tall images into a standard shape, clamp the ratio in the container and let object-fit crop. Embedding a 16:9 video and cropping images with aspect-ratio and object-fit practises the CSS, and keeping an element's aspect ratio explains it.
Ads, embeds and late content
- Ad slots: reserve a
min-heightfor each breakpoint, matching the most likely creative size. If the slot comes back empty, keep the space and show a house ad or a placeholder rather than collapsing it. - Embeds (videos, maps, social posts): wrap them in a container with a known
aspect-ratioormin-height. Third-party embeds often resize themselves after load, so a reserved box is the only defence. - Banners (cookie consent, "subscribe", app install): render them as fixed or sticky overlays, or reserve their space in the server HTML. Never push the article down a second after load.
- Personalised or A/B content: decide the variant on the server or reserve the space for it. Swapping blocks on the client after paint is both a flicker and a shift, as designing flags and A/B tests without layout shift covers.
Skeletons must have the final size
A skeleton that is shorter than the content it stands in for still shifts the page, just later. Give each skeleton row the same height, margins and image ratio as the real row. If content height varies, size the skeleton for the common case and keep variable parts, such as long text, below the fold or inside a box with a fixed or minimum height.
For long pages, content-visibility: auto skips rendering of off-screen sections. Pair it with contain-intrinsic-size: auto 600px so each section has a placeholder size and the scrollbar does not jump; the auto keyword makes the browser remember the real size once it has rendered the section.
Feeds: where new content goes
Appending older posts below the viewport during infinite scroll does not shift anything visible. Keep the loading indicator at the bottom at a fixed height so replacing it with posts does not move it around.
The dangerous case is new content at the top. When a live update brings new posts while the user reads, prepending them pushes the post they are reading down. Buffer them instead and show a "New posts" pill. When the user taps it, insert the buffered posts and scroll to the top. Because the posts are already in memory, the insert happens within 500 ms of the tap and counts as expected. If the tap triggered a fetch that took longer, the shift would count. The X home timeline design question builds this, and the news feed guide covers the rest of the feed.
Content that changes height above the viewport, such as an expanding comment thread or an image that finally loads further up, is partly handled by scroll anchoring: the browser adjusts the scroll position so the visible content stays put. Not every browser implements it, and virtualised lists manage scroll position themselves, so correct height estimates and stored media dimensions still matter.
Fonts and animations
A web font that swaps in with different metrics re-wraps every line of text. Options:
font-display: optional: the font is used only if it arrives very early; otherwise the fallback stays for that page view. No swap, no shift.- A metric-matched fallback: an
@font-facefor a local font withsize-adjust,ascent-overrideanddescent-overrideso it takes the same space as the web font.next/fontand tools such as Fontaine generate these values. - Preload the one or two font files used above the fold so the swap happens before first paint.
Loading web fonts with the FontFace API practises the controlled swap.
For animations, change transform and opacity. A transform does not change layout, so it never produces layout shift entries, while animating top, height or margin moves other elements on every frame. The cost difference is explained in reflow vs repaint.
Measuring layout shift
The Layout Instability API reports each shift, with the elements that moved, through PerformanceObserver. It is implemented in Chromium-based browsers.
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.hadRecentInput) continue; // expected, does not count
for (const source of entry.sources) {
console.log(entry.value.toFixed(4), source.node, source.previousRect, source.currentRect);
}
}
}).observe({ type: "layout-shift", buffered: true });In production, use the web-vitals attribution build, which applies the session-window rules and names the worst element:
import { onCLS } from "web-vitals/attribution";
onCLS(({ value, attribution }) => {
sendToAnalytics({
cls: value,
target: attribution.largestShiftTarget, // a CSS selector for the element
time: attribution.largestShiftTime,
loadState: attribution.loadState,
});
});Group the results by page template and release, then fix the largest targets first. In DevTools, the Performance panel marks each layout shift and highlights the elements that moved. Building a Web Vitals performance monitor puts this together, and fixing layout shifts from ads, fonts, images and late banners is the full diagnosis exercise.
Follow-up questions interviewers ask
Why is CLS good in Lighthouse but poor in the field?
Lighthouse measures one simulated page load with a clean cache and no scrolling. Field CLS covers the whole visit: lazy images loading during scroll, ads, consent banners, slow fonts and live feed updates. Many shifts only happen after load.
Does a shift below the fold count?
Only the visible part of the viewport counts. An element moving entirely off-screen adds nothing. It starts to count once the user scrolls and it moves while visible.
Does expanding an accordion on click hurt CLS?
No, if the layout change happens within 500 ms of the click. A slow request that expands the section later, or a long height animation, can fall outside that window and count.
Is loading="lazy" itself a cause of layout shift?
loading="lazy" itself a cause of layout shift?No. The missing dimensions are. A lazy image with width and height reserves its box from the start and loads into it.
How do you prevent shift when the content height is unknown?
Get the size earlier: store media dimensions at upload, render server-side with the real content, or reserve a minimum height and let content grow below the viewport. If none is possible, place the late content below what the user is reading.
Mistakes to avoid
Lazy-loading images without
widthandheight, or settingheightin CSS without the attribute ratioCollapsing an empty ad slot after it was reserved
Prepending live posts above the reading position
Skeletons that are a different size from the content
Animating
toporheightwheretransformwould doTesting CLS only in the lab on a fast laptop
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Fix layout shifts from ads, web fonts, images and late bannersHard40 min
- Design the X (Twitter) home timeline: For You and Following tabs, a new-posts pill, infinite scroll and optimistic likesHard55 min
- Embed a responsive 16:9 video and crop images to fit with
aspect-ratioandobject-fitEasy15 min - Load web fonts with the FontFace API: a timeout, a fallback and a single class swapMedium35 min
- Implement a performance monitor measuring Web Vitals and reporting metricsMedium45 min
- Design a news article page like the New York Times: ads without layout shift, a metered paywall, speed, SEO and sharingHard55 min