Skip to content

Cumulative Layout Shift from Images/Ads Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Cumulative Layout Shift from Images/Ads Fix. We cover key concepts, practical examples, and best practices.

The Problem

Images and ads load asynchronously and push content down when they render, causing Cumulative Layout Shift (CLS). A poor CLS score frustrates users who lose their reading position and accidentally click the wrong elements.

Quick Fix

Step 1: Set explicit image dimensions

<!-- Wrong — no dimensions, browser reserves 0x0 space -->
<img src="hero.jpg" alt="Hero">

<!-- Right — explicit width and height -->
<img src="hero.jpg" alt="Hero" width="1200" height="600">

<!-- Or use CSS aspect-ratio -->
<img src="hero.jpg" alt="Hero" style="aspect-ratio: 1200/600; max-width: 100%; height: auto;">

Step 2: Reserve space for ads

<!-- Wrong — no space reserved, ad loads and shifts content -->
<div class="ad-container">
    <!-- Ad loads here dynamically -->
</div>

<!-- Right — fixed dimensions, content does not shift -->
<div class="ad-container" style="min-width: 300px; min-height: 250px;">
    <!-- Ad loads within reserved space -->
</div>

<!-- With responsive sizing -->
<style>
    .ad-container {
        min-height: 100px;
        width: 100%;
    }

    @media (min-width: 768px) {
        .ad-container {
            min-height: 250px;
        }
    }
</style>

Step 3: Use CSS aspect-ratio for responsive media

/* Wrong — no aspect ratio, container collapses */
.media-wrapper iframe {
    width: 100%;
}

/* Right — maintain aspect ratio */
.media-wrapper {
    position: relative;
    aspect-ratio: 16 / 9;
    width: 100%;
}

.media-wrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Step 4: Handle dynamic content insertion

// Wrong — inserting content above existing content causes shift
function insertBanner() {
    const banner = document.createElement('div');
    banner.textContent = 'Special offer!';
    banner.style.background = 'yellow';
    const container = document.getElementById('content');
    container.prepend(banner); // Shifts everything down
}

// Right — reserve space or insert below the fold
function insertBanner() {
    const placeholder = document.getElementById('banner-placeholder');
    if (placeholder) {
        const banner = document.createElement('div');
        banner.textContent = 'Special offer!';
        banner.style.background = 'yellow';
        placeholder.replaceWith(banner);
    }
}

// Or insert after the main content (below the fold)
function insertBanner() {
    const afterContent = document.getElementById('after-content');
    if (afterContent) {
        const banner = document.createElement('div');
        banner.textContent = 'Special offer!';
        afterContent.appendChild(banner);
    }
}

Step 5: Load web fonts without layout shift

/* Wrong — fallback and custom fonts have different metrics */
body {
    font-family: 'CustomFont', sans-serif;
}

/* Right — use size-adjust to match metrics */
@font-face {
    font-family: 'CustomFont';
    src: url('/fonts/custom.woff2') format('woff2');
    font-display: swap;
    size-adjust: 95%;
    ascent-override: 90%;
    descent-override: 20%;
}

/* Or use font-display: optional to avoid FOIT/FOUT entirely */
@font-face {
    font-family: 'CustomFont';
    src: url('/fonts/custom.woff2') format('woff2');
    font-display: optional;
}

Prevention

  • Always set width and height on images
  • Reserve fixed space for ads, embeds, and dynamic widgets
  • Use aspect-ratio CSS for responsive media embeds
  • Avoid inserting content above existing page content
  • Use font-display: optional or size-adjust for custom fonts

Common Mistakes with cls fix

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world PERF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### How is CLS calculated?

CLS sums the score of every unexpected layout shift during the page lifecycle. Each shift score = impact fraction (portion of viewport affected) x distance fraction (how far elements moved). A score under 0.1 is good.

Do lazy-loaded images cause CLS?

Yes, unless you set dimensions. Without width/height, the browser reserves 0x0 space. When the lazy image loads, it expands and shifts content. Fix: always set width and height attributes on lazy-loaded images.

Can CLS be caused by dynamic CSS?

Yes. Animating layout-triggering properties (top, left, width, height, margin) causes CLS. Also, inserting CSS classes that change element dimensions after the page has painted can shift content.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro