🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Performance••By Komal Nakrani

Cumulative Layout Shift in Astro: How to Prevent It

Fix cumulative layout shift in Astro: sized images with astro:assets, font fallbacks with the Fonts API, reserved space for embeds, ads, islands and banners.

#Astro#Cumulative Layout Shift#Core Web Vitals#Performance#Images

Cumulative layout shift (CLS) measures how much visible content moves while a page loads, and a score of 0.1 or less counts as good. In Astro, most layout shift comes from four sources: images without dimensions, web fonts swapping in, embeds and ads that load late, and islands or banners that render after the first paint. Each one has a direct fix: let astro:assets set image dimensions, use the Fonts API’s metric-matched fallbacks, and reserve space for anything that arrives later.

Astro starts with an advantage because it sends complete HTML with no JavaScript by default, so there is no client-side render that pushes content around. This guide shows where shifts still creep in and the code that stops them.

Key Takeaways

  • CLS thresholds: 0.1 or less is good, above 0.25 is poor, measured at the 75th percentile of real visits.
  • <Image /> and <Picture /> from astro:assets write width and height for local images automatically. Remote images need explicit dimensions or inferSize.
  • The Fonts API in astro.config.mjs generates fallback fonts with adjusted metrics, which removes most font-swap shift.
  • Give embeds, ads, cookie banners and islands a fixed box with aspect-ratio or min-height before they load.
  • Prefer transform and opacity for animations; animating height or top causes shifts.

How cumulative layout shift is measured

The browser records a layout shift whenever a visible element changes position between two frames without a user input causing it. Each shift scores the fraction of the viewport that moved multiplied by how far it moved. CLS groups shifts into session windows (bursts with gaps under one second, capped at five seconds) and reports the worst window for the whole page visit.

Two details matter in practice:

  1. Shifts within 500 ms of a click, tap or key press do not count. Opening an accordion when someone clicks it is fine.
  2. CLS covers the entire visit, not just the load. A banner that slides in after 10 seconds, or content that jumps during scroll, still adds to the score.

Google uses field data (the Chrome User Experience Report) for Core Web Vitals, so lab tools such as Lighthouse are a guide, not the final word. The Astro performance guide covers the other two metrics, LCP and INP.

Why Astro pages start with low layout shift

Many layout shifts on JavaScript-heavy sites happen because the server sends an empty shell, then the client renders content in stages. Astro renders the full page to HTML at build time or on the server, so text, headings and structure arrive in the first response and stay where they are.

That leaves the shifts caused by things that load after the HTML: images, fonts, third-party embeds and any island that renders different markup on the client. The rest of this guide handles each one.

Fix 1: Give every image dimensions

An <img> without width and height has zero height until the file downloads, then pushes everything below it down. The browser can reserve the right space only if it knows the aspect ratio in advance.

Astro’s <Image /> component handles this for local images. Import the file and Astro reads its dimensions at build time:

---
// src/components/Hero.astro
import { Image } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Image src={hero} alt="Studio workspace at dusk" widths={[640, 1024, 1600]} sizes="100vw" />

The output includes width and height attributes, so the browser computes the aspect ratio and reserves the box immediately, even when CSS scales the image with width: 100%; height: auto.

Remote images are different, because Astro cannot see the file at build time. Either pass dimensions yourself, or let Astro fetch them with inferSize:

---
// src/components/RemoteCover.astro
import { Image } from 'astro:assets';
const { url, alt } = Astro.props;
---
<Image src={url} alt={alt} width={1200} height={630} />
<!-- or, when you do not know the size: -->
<Image src={url} alt={alt} inferSize />

Remote domains must be allowed in image.domains or image.remotePatterns for optimization. If you forget dimensions on a remote image, Astro stops the build with a missing dimensions error, which is covered in fixing missing image dimensions.

For responsive layouts, set a default image layout in the config so every image scales inside its container while keeping its reserved ratio:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    layout: 'constrained',
    responsiveStyles: true,
  },
});

constrained images scale down to fit their container but never exceed their real size. responsiveStyles: true adds the small global styles that make this work. The responsive images tip shows widths and sizes in more depth.

Images in Markdown and MDX go through the same pipeline when they use relative paths (![Alt](./photo.jpg)), so blog posts get dimensions too. Images in public/ are not processed, so give those width and height by hand or move them into src/.

Fix 2: Stop web fonts from shifting text

When a web font loads, text first renders in a fallback font, then swaps. If the fallback has different letter widths or line heights, paragraphs rewrap and everything below moves. On text-heavy pages this is often the largest source of cumulative layout shift.

The Fonts API, configured in astro.config.mjs, fixes this by generating a fallback @font-face with size and metric overrides that match your web font:

// astro.config.mjs
import { defineConfig, fontProviders } from 'astro/config';

export default defineConfig({
  fonts: [
    {
      provider: fontProviders.google(),
      name: 'Inter',
      cssVariable: '--font-body',
      weights: [400, 700],
      fallbacks: ['sans-serif'],
    },
  ],
});

Then load it in your layout’s head, preloading only the files the first screen needs:

---
// src/layouts/BaseLayout.astro
import { Font } from 'astro:assets';
---
<html lang="en">
  <head>
    <Font cssVariable="--font-body" preload />
  </head>
  <body>
    <slot />
  </body>
</html>
/* src/styles/global.css */
body {
  font-family: var(--font-body);
}

Astro downloads the font files at build time, serves them from your own domain, and creates an adjusted fallback based on the generic family you list (keep fallbacks ending in a generic name such as sans-serif). The fallback text takes up almost the same space as the real font, so the swap barely moves anything.

If you self-host fonts manually instead, add size-adjust, ascent-override and descent-override to a fallback @font-face, and preload the main weight. The styling docs show how Komal themes wire fonts into design tokens.

Fix 3: Reserve space for embeds, ads and iframes

Third-party content (YouTube videos, maps, social embeds, ad slots) typically loads after the page and has no intrinsic size until it does. Reserve its box in CSS before it arrives:

---
// src/components/VideoEmbed.astro
interface Props { id: string; title: string }
const { id, title } = Astro.props;
---
<div class="video">
  <iframe
    src={`https://www.youtube-nocookie.com/embed/${id}`}
    title={title}
    loading="lazy"
    allow="accelerometer; encrypted-media; picture-in-picture"
    allowfullscreen
  ></iframe>
</div>

<style>
  .video {
    aspect-ratio: 16 / 9;
    width: 100%;
  }
  .video iframe {
    width: 100%;
    height: 100%;
    border: 0;
  }
</style>

For ads and widgets with variable heights, set min-height to the most common size. A slot that sometimes stays empty is better than one that pushes the article down when it fills. Avoid inserting embeds above existing content; put them where they will not move what the reader is already looking at.

Fix 4: Keep islands from changing size on hydration

An island renders its HTML on the server first. If the client version renders something different (a loaded list replacing an empty one, a skeleton replaced by taller content), the page shifts on hydration.

Three habits prevent it:

  1. Render the real content on the server. Fetch data in the Astro component’s frontmatter and pass it as props, so the server HTML and hydrated HTML match.
  2. Size placeholders correctly. If a component must load data in the browser, give its container a min-height close to the final size.
  3. Use client:only carefully. It renders nothing on the server, so the box is empty until JavaScript runs. Wrap it in a sized container, or use a fallback slot with the same dimensions.
---
// src/pages/pricing.astro
import PriceCalculator from '../components/PriceCalculator.jsx';
---
<div style="min-height: 420px">
  <PriceCalculator client:only="react">
    <div slot="fallback" style="height: 420px">Loading calculator</div>
  </PriceCalculator>
</div>

Server islands (server:defer) work the same way: the fallback slot should match the final content’s size as closely as possible.

Cookie banners, announcement bars and newsletter prompts often appear after load. If they push the page down, they add shift on every visit. Prefer overlays that do not move content:

/* src/styles/global.css */
.consent-banner {
  position: fixed;
  inset: auto 0 0 0;
}

A fixed banner at the bottom of the viewport overlays content instead of displacing it. If an announcement bar must sit in the flow at the top, render it in the HTML from the start (so it is part of the first paint) rather than injecting it with JavaScript.

For animation, use transform and opacity. Animating top, margin, height or width moves surrounding layout and counts as shift; transforms do not.

How to find what is shifting

  1. Chrome DevTools Performance panel. Record a page load; layout shifts show in the timeline with the elements that moved.
  2. Lighthouse. The “Avoid large layout shifts” audit lists the biggest contributors.
  3. The web-vitals library. Log CLS with attribution from real visits:
// src/scripts/vitals.ts
import { onCLS } from 'web-vitals/attribution';

onCLS(({ value, attribution }) => {
  console.log('CLS', value, attribution.largestShiftTarget);
});

Load it with a <script> tag in your layout and Astro bundles it. Send the values to your analytics if you want field data beyond what Search Console reports.

  1. Test with a slow connection and cache disabled. Shifts that never appear on a fast laptop often show up on a throttled mobile profile.

A layout shift checklist for Astro

  • Every image uses astro:assets, or has width and height if it lives in public/
  • Remote images have dimensions or inferSize
  • Fonts use the Fonts API with a generic fallback, or manual metric overrides
  • Embeds and iframes sit in boxes with aspect-ratio
  • Ad and widget slots have a min-height
  • client:only islands and server islands have sized fallbacks
  • Banners overlay with position: fixed instead of pushing content
  • Animations use transform and opacity

Every Komal theme uses astro:assets for its images and static HTML output, so these basics are in place when you start, but anything you add (embeds, ads, consent tools) still needs the space-reserving fixes above. For the official reference, see the Astro images guide and web.dev’s CLS article.

FAQ

What is a good cumulative layout shift score?

A CLS of 0.1 or less is good, between 0.1 and 0.25 needs improvement, and above 0.25 is poor. Google measures it at the 75th percentile of real page visits, split by mobile and desktop.

Does Astro prevent layout shift automatically?

Partly. Astro sends complete HTML and its <Image /> component sets width and height for local images, which removes the most common causes. Fonts, third-party embeds, ads and late-loading UI can still shift the page unless you reserve space for them.

Why does my Astro site have layout shift from fonts?

When a web font loads, text swaps from the fallback font, and different letter widths cause rewrapping. Use the Fonts API in astro.config.mjs with a generic fallback such as sans-serif, and Astro generates a metric-adjusted fallback that keeps text in place during the swap.

How do I fix layout shift from images in Astro?

Use <Image /> or <Picture /> from astro:assets with imported local images so Astro writes the width and height. For remote images, pass width and height or inferSize. For images in public/, add the dimensions to the <img> tag yourself.

Do Astro islands cause layout shift?

They can if the client renders different markup from the server, or if a client:only component has no sized placeholder. Render data on the server where possible, and give client-only and server islands a fallback with the same dimensions as the final content.