How to Fix Cumulative Layout Shift (CLS) in WooCommerce and Shopify Product Grids

In this article (11)
A product grid may look perfectly stable when it first appears, then move just as a shopper tries to select a size or tap Add to cart. Sometimes the cause is obvious, like an image loading into an empty container. Other times it is a price changing after an AJAX response, a review widget appearing late, or a brand font changing where a product title wraps.
These problems are worth investigating on both WooCommerce and Shopify stores. Fortunately, many can be reduced with a combination of sensible HTML, CSS, theme-level checks, and measurement—not a new performance plugin.
This guide explains what Cumulative Layout Shift measures, how to find the source of a shift, and how to make product grids more visually stable. The examples are educational patterns: adapt selectors and templates to your theme, and test them before deploying.
What is CLS, and what score should you aim for?
Cumulative Layout Shift (CLS) is a Core Web Vital that measures unexpected visual movement during a page’s lifecycle. A shift is recorded when a visible element changes position between rendered frames. CLS uses the largest burst (session window) of unexpected shifts, not simply the sum of every movement on the page.
Google’s recommended thresholds are:
| CLS score | Assessment |
|---|---|
| 0.10 or less | Good |
| Greater than 0.10 and up to 0.25 | Needs improvement |
| Greater than 0.25 | Poor |
These thresholds are evaluated at the 75th percentile of page loads, separately for mobile and desktop. A score of exactly 0.00 in one Lighthouse run does not prove your storefront has no layout shifts in real-world sessions.
Some layout changes immediately following user input are expected. Shifts within approximately 500 milliseconds of qualifying user interactions are generally excluded from CLS, but delayed AJAX updates may still count. Regardless of the metric, unexpected movement can still frustrate users.
Sources: Google: Cumulative Layout Shift · Core Web Vitals thresholds
Step 1: Identify the actual source of the shift
Before editing CSS, reproduce the issue. A page that shifts because of a late review widget will not be fixed by changing image aspect ratios.
- Open a collection or shop page in Chrome, ideally in a staging store.
- Open DevTools → Performance and record a page load. Check the layout-shift events and their highlighted elements. The Rendering panel can also highlight layout-shift regions as they occur.
- Repeat the test with a mobile-sized viewport and throttled network, and interact with sorting, filters, swatches, and pagination.
- Compare the test with PageSpeed Insights. Where available, its real-user field data may differ from a single lab test because shoppers have different devices, networks, and interactions.
For quick debugging, you can also run this snippet in DevTools Console before reproducing the issue:
if (PerformanceObserver.supportedEntryTypes.includes('layout-shift')) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.hadRecentInput) continue;
console.log('Unexpected layout shift', {
score: entry.value,
time: Math.round(entry.startTime),
elements: entry.sources?.map((source) => source.node)
});
}
});
observer.observe({ type: 'layout-shift', buffered: true });
}
This logs individual unexpected shift entries; it does not calculate the official CLS session-window score. Use DevTools or an appropriate Web Vitals measurement library for that. The nodes listed as shifted elements are clues, not always the cause: an inserted badge above a card may move the product title below it.
Sources: Google: Debug layout shifts · Chrome DevTools Performance features
Step 2: Reserve space for product images
An <img> element without known dimensions may have no reserved height before its image data arrives. Content below it can move down when the browser finally determines the image’s size.
Start with width and height attributes
The browser can calculate an image’s initial aspect ratio from its HTML width and height attributes—even when responsive CSS changes the displayed size:
<img
src="/images/example-product.webp"
alt="Navy cotton shirt"
width="800"
height="1000"
class="product-card__image"
>
.product-card__image {
display: block;
max-width: 100%;
height: auto;
}
The values above describe the example image’s actual ratio. They are not universal dimensions to paste onto every image.
Use a consistent media box when your design requires one
For a fashion grid with intentionally uniform portrait cards, a wrapper can reserve a 4 / 5 region:
.product-card__media {
position: relative;
aspect-ratio: 4 / 5;
overflow: hidden;
background: #f4f4f4;
}
.product-card__media > img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
With this approach, the wrapper reserves the card’s media height while object-fit: cover crops images to fill it. If showing every edge of the product matters, switch to object-fit: contain and accept blank space around some images. Do not force a 4 / 5 crop on stores with a different intended image presentation.
A skeleton background or shimmer may make loading feel clearer, but the reserved dimensions—not the animation—are what protect the layout.
Source: Google: Optimize CLS — images and reserved space
Step 3: Apply the image fix in Shopify
Before manually writing <img> tags, inspect your theme’s existing product-card snippet. Shopify’s image_url and image_tag Liquid filters support responsive images, and image_tag normally outputs width and height attributes automatically.
A simplified product-card media example is:
{% if product.featured_image %}
<div class="product-card__media">
{{ product.featured_image
| image_url: width: 900
| image_tag:
class: 'product-card__image',
widths: '300, 450, 600, 900',
sizes: '(min-width: 990px) 25vw, (min-width: 600px) 33vw, 50vw'
}}
</div>
{% endif %}
Use the CSS from Step 2 if your design uses a uniform 4 / 5 media box. Adjust the sizes calculation to your theme’s real grid columns and gutters; it is an illustration, not a universal value. Review image-loading priority for visible products instead of indiscriminately lazy-loading the first row.
Important: If your current theme already uses image_tag and reserves appropriate image space, adding another wrapper may be unnecessary. Inspect the rendered HTML first. A theme’s CSS can still override good markup in ways that create instability.
Sources: Shopify: Prevent image layout shift · Shopify: image_tag filter
Step 4: Apply the image fix in WooCommerce
WordPress image functions commonly generate responsive image markup with dimensions, srcset, and sizes. WooCommerce product APIs build on that image functionality, so you should generally keep the native output rather than replacing it with a hand-built image URL.
For example, inside a custom PHP WooCommerce product-card template where $product is a valid WC_Product object:
<?php if ( $product instanceof WC_Product ) : ?>
<div class="product-card__media">
<?php
echo $product->get_image(
'woocommerce_thumbnail',
array( 'class' => 'product-card__image' )
);
?>
</div>
<?php endif; ?>
Use the media-box CSS from Step 2 if it matches your design. The example relies on WooCommerce’s existing image rendering; it does not require writing width and height attributes manually. The resulting HTML should still be inspected for the specific product image, thumbnail size, theme overrides, and missing-image fallback.
For a standard WooCommerce shop loop, the theme might already render the product thumbnail correctly. If so, fix only the problematic styling or custom AJAX replacement markup. Block-based product grids and custom page builders may have different structure and controls, so avoid assuming that one selector works across all WooCommerce sites.
Sources: WordPress: wp_get_attachment_image() · WooCommerce: Product get_image() API · WooCommerce: Image sizing for theme developers
Step 5: Prevent badges, ratings, and prices from pushing cards around
Images are only part of the problem. A product card often includes elements that change after initial render:
- Sale and stock badges: A script inserts a badge above the title rather than positioning it inside the image.
- Ratings and reviews: A third-party widget mounts after the rest of the product card is painted.
- Prices: A variable product, promotion, or currency display replaces one line of text with two.
- Shipping information: A delivery promise appears after an asynchronous request.
Overlay a badge instead of inserting it into the card flow
<div class="product-card__media">
<!-- Product image goes here -->
<span class="product-card__badge">Sale</span>
</div>
.product-card__media {
position: relative;
}
.product-card__badge {
position: absolute;
top: 0.75rem;
left: 0.75rem;
z-index: 1;
}
Because the badge is positioned inside the already-reserved media region, displaying it need not increase the card’s height. Keep the badge readable and check for overlap with other controls.
Reserve realistic space for content that arrives later
<div class="product-card__rating" aria-label="Product rating">
<!-- Review widget or server-rendered rating goes here -->
</div>
<div class="product-card__price">
<!-- Current price and optional compare-at price go here -->
</div>
.product-card__rating {
min-height: 1.5rem;
}
.product-card__price {
line-height: 1.4;
min-height: 2.8em; /* Example: space for roughly two lines */
}
These are starting dimensions to test, not guarantees of zero shift. If the widget uses two lines on mobile, or a localized price wraps to three lines, the container can still grow. Ideally, render known prices and ratings server-side; when content truly must load asynchronously, estimate its required height using actual layouts across breakpoints.
A min-height rule reduces movement only when the eventual content fits in the reserved space. Reserving too much can create needless empty areas, so measure the trade-off.
Source: Google: Reserve space for late-loading content
Step 6: Handle font swaps without relying on magic numbers
Custom fonts can cause product titles or prices to rewrap when the initial fallback font is replaced. A title changing from two lines to three may change the card’s height and move other elements.
A useful starting point is to choose a fallback font that is visually similar to the brand font and evaluate the loading strategy:
@font-face {
font-family: 'Store Sans';
src: url('/fonts/store-sans.woff2') format('woff2');
font-display: swap;
}
.product-card__title {
font-family: 'Store Sans', Arial, sans-serif;
line-height: 1.4;
}
font-display: swap makes fallback text visible while the custom font loads, but it does not prevent CLS by itself. If visual stability is the priority and using a fallback font for the initial visit is acceptable, font-display: optional is another strategy to test.
For more advanced control, CSS font-face descriptors such as size-adjust, ascent-override, descent-override, and line-gap-override can help match fallback-font metrics to the actual web font. Do not copy arbitrary percentages from a tutorial: the correct values depend on the font files and fallback font. Browser support also needs checking, especially for individual metrics overrides.
Treat these as measured refinements after establishing that font loading is actually responsible for your layout shift.
Sources: Google: Optimize web fonts · Google: Font best practices · MDN: size-adjust
Step 7: Keep AJAX filters and skeleton grids stable
Dynamic collections introduce another class of layout shift. Consider a shopper filtering a product grid by size or price:
- The existing products disappear.
- The container collapses because its items are gone.
- A loading spinner appears.
- New product cards arrive and push the content back down.
Even when the final products load quickly, the intervening collapse can feel jarring.
A better approach is to keep the existing grid’s layout or a similarly sized loading state while the replacement results are being fetched. For example:
.product-grid-shell {
position: relative;
}
.product-grid-shell[aria-busy='true']::after {
content: '';
position: absolute;
inset: 0;
background: rgb(255 255 255 / 55%);
pointer-events: none;
}
Your JavaScript can set aria-busy="true" on the shell while fetching and replace the results only when ready, then remove that state. This is only the visual loading pattern; it is not a complete filtering implementation. Keep keyboard focus, loading announcements, errors, and empty-result states accessible.
If you show skeleton cards instead, their grid columns, image ratios, and expected text regions should resemble the real product cards. For empty-result pages or dramatically different result counts, the layout may legitimately change. Avoid locking the container to a permanent oversized height simply to manipulate a score.
Source: Google: Avoid inserting new content unexpectedly
Step 8: Test the change in real browsing scenarios
After each adjustment, test again rather than assuming the CSS solved everything. Use this practical checklist:
- Image dimensions are present in the rendered HTML, or the media area has a reliable reserved aspect ratio.
- The first product row stays stable on a slow network and a narrow mobile viewport.
- Sale badges, rating widgets, and price updates do not unexpectedly push neighboring content.
- Brand fonts do not introduce noticeable title or price wrapping changes.
- Filters, sorting, pagination, and infinite-scroll interactions are tested after initial page load.
- Products with long names, sale prices, missing images, and translated text are covered.
- Field CLS is reviewed where sufficient real-user data is available, not inferred from one lab score.
For a meaningful comparison, document the URL or page type, device conditions, test settings, and before/after results. Repeat lab runs because a single number can vary. Monitor real-user data after deployment when the store receives enough traffic.
Common CLS fixes that can backfire
| Quick fix | Why it may fail | Better approach |
|---|---|---|
Force every image to height: 300px |
Crops or distorts product media across layouts | Use correct dimensions or an intentional, responsive aspect ratio |
| Add shimmer to every loading image | An animation alone does not reserve space | Reserve the media box before download |
Give every review widget min-height: 24px |
Widgets can be taller on some devices | Measure their actual size at relevant breakpoints |
| Copy font metric override percentages | Font measurements differ by family and weight | Calculate and test overrides for the actual font pairing |
| Set a huge fixed height on the grid | Produces unnecessary whitespace for fewer results | Preserve the current grid or use realistic loading placeholders |
| Optimize only the first page-load screenshot | AJAX changes and late-loading content may still shift | Test the full page lifecycle and real interactions |
Conclusion
Improving CLS in WooCommerce and Shopify product grids is less about adding a new tool and more about making layout decisions predictable. Start by diagnosing the specific movement. Keep the platform’s native responsive image markup, reserve space where content loads later, avoid uncontrolled font swaps, and make asynchronous updates visually stable.
The goal isn’t to manufacture a perfect 0.00 screenshot. It’s to create product grids that stay usable and comfortable while real customers browse—and to verify that improvement with the right measurements.
Official documentation and further reading
- Google web.dev — Cumulative Layout Shift (CLS)
- Google web.dev — Optimize Cumulative Layout Shift
- Google web.dev — Debug layout shifts
- Chrome DevTools — Performance features reference
- Shopify — Prevent image layout shift
- Shopify Liquid —
image_tag - WordPress Developer —
wp_get_attachment_image() - WooCommerce Developer — Image sizing for theme developers
- Google web.dev — Optimize web fonts
- MDN —
size-adjustfont descriptor


