Skip to main content

Prevent image layout shift with width and height

Always include width and height attributes on <img> tags. For Shopify themes, use the image_tag Liquid filter, which automatically adds these attributes.

Missing width and height attributes on images is one of the most common causes of Cumulative Layout Shift (CLS) on the web. When the browser doesn't know an image's dimensions, it reserves no space for it. When the image finally loads, the browser must shift surrounding content to make room, creating a poor user experience.


Without dimensions, the browser's loading process results in layout shift. The process proceeds as follows:

  1. Parse the HTML and encounter an <img> tag.
  2. Assume the image has a height of 0 because dimensions are unknown.
  3. Render the page with no space reserved for the image.
  4. Download the image file.
  5. Discover the image's actual dimensions.
  6. Force a layout shift by pushing content down to make room for the image.

This causes high CLS scores and user frustration.


Always include width and height attributes on <img> tags. Combined with CSS that sets max-width: 100% and height: auto, the browser can calculate the aspect ratio and reserve the correct amount of space before the image downloads.

For Shopify themes, use the image_tag Liquid filter, which automatically adds the correct width and height attributes based on the original image's aspect ratio.


Basic HTML with dimensions and CSS:

<img src="image.jpg" width="800" height="600" alt="Product" />

Combined with CSS:

img {
max-width: 100%;
height: auto;
}

The browser can calculate the aspect ratio and reserve the correct amount of space before the image downloads.

Shopify Liquid approach:

{{ product.featured_image
| image_url: width: 800
| image_tag: alt: product.title
}}

Generates:

<img
src="...image-800.jpg"
width="800"
height="600"
srcset="..."
sizes="..."
alt="Product Title"
/>

CSS aspect-ratio approach (modern browsers):

.image-container {
aspect-ratio: 16 / 9;
}

.image-container img {
width: 100%;
height: auto;
}

For CSS background-style layouts:

.image-container {
width: 100%;
height: 400px;
overflow: hidden;
}

.image-container img {
width: 100%;
height: 100%;
object-fit: cover;
}

This sets the container dimensions and crops the image to fit.


  • The Chrome DevTools Performance panel shows all layout shifts with screenshots. Look for Layout Shift entries.
  • Use Live metrics in the Performance panel to see the CLS breakdown.
  • Visually observe with network throttling enabled.
  • Use the Rendering tab and Layout Shift Regions to visually highlight shifting elements.


Was this page helpful?