Tips for resolving Layout Shift issues in responsive images utilizing the picture & source HTML tags

One issue I encountered with the <source> element is that even when specifying the width and height attributes for both the <source> and image fallback, there is still significant layout shift. This could be due to using images with varying dimensions, resulting in noticeable differences in size.

To provide a simplified example:

<picture>
  <source
  sizes="(min-width: 900px) 900px, (min-width: 640px) 600px, (min-width: 340px) 300px, calc(100vw - 56px)"
  srcset="/images/demo-300.avif 300w, /images/demo-600.avif, /images/demo-900.avif 900w"
  type="image/avif" width="300" height="400" />

  <img src="images/demo-300.jpg" width="300" height="400" />
</picture>

Unlike the <img> tag where specifying the intrinsic size helps browsers allocate space for rendering, this approach doesn't seem to work with the <source> tag. Are there any suggested workarounds to address this behavior?

Answer №1

There seems to be an error occurring here, even though width and height attributes have been provided for the sources and images. A layout shift is still observed, especially when images of varying dimensions are loaded. To prevent this issue, we can wrap the image in a container that maintains the same aspect ratio. Here's the necessary CSS code snippet:

<style>
  .container {
    position: relative;
    width: 100%;
  }

  .aspect-ratio-placeholder {
    width: 100%;
    padding-top: calc(400 / 300 * 100%);
  }

  .image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>

<div class="container">
  <div class="aspect-ratio-placeholder"></div>
  <picture class="image">
    <source
      sizes="(min-width: 900px) 900px,
        (min-width: 640px) 600px,
        (min-width: 340px) 300px,
        calc(100vw - 56px)"
      srcset="/images/demo-300.avif 300w,
        /images/demo-600.avif,
        /images/demo-900.avif 900w"
      type="image/avif"
      width="300"
      height="400"
    />
    <source
      sizes="(min-width: 900px) 900px,
        (min-width: 640px) 600px,
        (min-width: 340px) 300px,
        calc(100vw - 56px)"
      srcset="/images/demo-300.webp 300w,
        /images/demo-600.webp 600w,
        /images/demo-900.webp 900w"
      type="image/webp"
      width="300"
      height="400"
    />
    <source
      sizes="(min-width: 900px) 900px,
        (min-width: 640px) 600px,
        (min-width: 340px) 300px,
        calc(100vw - 56px)"
      srcset="/images/demo-300.jpg 300w,
        /images/demo-600.jpg 600w,
        /images/demo-900.jpg 900w"
      type="image/jpg"
      width="300"
      height="400"
    />
    <img src="images/vila-demo-300.jpg" width="300" height="400" />
  </picture>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to access input fields in a form without knowing the specific name

I am facing a challenge with a dynamically generated form using jQuery Ajax, where the input field names and values are also dynamic. I need to figure out how to update these fields using PHP. One issue I encounter is that upon form submission, I am unsur ...

How can you modify the color of a card in React by mapping through an array and evaluating its value?

I'm attempting to modify the color of a card depending on the current slot value, which is an object in an array. While I am iterating through each card, I want to adjust the background color of the card based on this value. However, my current method ...

Why are my Bootstrap nav-tabs not showing tab-content in MVC?

I'm dynamically creating tab navigation from controllers using a list. <div class=""row> <div class="col-xl-3"> <!-- Tabs nav --> <div class="nav flex-column nav-pills nav-pills-custom" id="v-p ...

What is the best way to incorporate data from my Input field into my Vue.JS application's existing data structure

Struggling with integrating new users into my personal project, particularly in passing input values (userName and userAge) to the parent element for addition to playersData. Here is a sample code snippet from the child component: `<template> <d ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Automotive Dealership API by Edmunds

I am having some trouble with the Edmunds API data. I can't seem to get the JSON to display when using the example code provided. It just shows up as a blank page. I am quite new to working with API's and would really appreciate some guidance on ...

The focus is on the last row that was selected

I've noticed that when I check and select a row in ui-grid, only the last selected row is focused with a background color. Should all rows be automatically painted by default? Thank you. ...

What causes my image to overlap my navigation bar when I rotate it?

Is there a way to rotate images in CSS without causing them to overlap with other elements on the page? When I try to adjust the rotation property, the image sticks to the top of the page and overlaps the navigation bar. Below is the code snippet: HTML C ...

Implementing a clickable search icon within a form input field using CSS: a guide

I have added a search icon to the form input field. Check it out here: https://i.sstatic.net/pnv6k.jpg #searchform { position: relative; } #searchform:before { content: "\f118"; font-family: "pharma"; right: 0px; position: absolute; ...

Adding dropdown values to text area

I'm encountering a simple issue. My goal is to allow users to select values from a dropdown menu and have those values added to a text area. Additionally, users should be able to input extra content in the text area. Here's what I want: the user ...

What is the method for displaying an asterisk in a select box option?

Is there a way to append an asterisk after the first option in a select element? Here is my html <select class="form-control textyformcontrol"> <option selected>Service area</option> <option>First Option</option> &l ...

Arranging a Table with unconventional column headings using a hash map in Java

As a newcomer in the world of Java, I have been able to successfully set up a table with regular headers using a hash map. However, I now face the challenge of setting irregular headers in the table by grouping multiple columns under one main heading. //~ ...

Rgd: Double-Sided Horizontal Slide Control

While browsing the internet, I came across several examples of horizontal sliders with adjustable values. For example, if I set the maximum value as 100 and move the slider 10 sectors to the left, each sector would decrease by 10. What I am trying to ach ...

Phonegap Application: Page design gets distorted following keyboard input

After a user enters login details and the next page loads, the layout shifts as shown in the image below. The entire app layout breaks and the view moves down to accommodate the size of the onscreen keyboard. This issue persists unless the orientation is ...

Guide on showing long blocks of text in MySQL without formatting restrictions

I've come across a problem that I can't seem to solve anywhere. After storing data from a topic or comment in the database, the message is stored in a longtext format. However, when the longtext shows fine in the table (with enters and multiple ...

Error encountered on Facebook Like button: The large button is failing to show the total number of likes received

Despite functioning flawlessly for months, the large Facebook Like button has suddenly stopped showing the number of "Likes". Strangely, the compact version is still working fine, but the larger button is concealing the count. I am using a Mac and have obs ...

Increase the size of the image while ensuring the content on the right remains proportionate

I have a challenge with managing two different sizes of images (vertical and horizontal) that need to remain the same size. I am attempting to create a container that can hold the image without affecting the surrounding content, while also possibly using o ...

Divide data into an HTML table and merge it with header information

My HTML form contains an interactive HTML table where users can add/delete rows. I am sending this data to a Google Sheet and need to store the row information with corresponding header details. Each time a user submits the form, a new row is added to the ...

Tips for designing a HTML form using classes

I need help styling this form using CSS because I have similar areas like a search submit button that require different classes. Any assistance would be greatly appreciated. <perch:form id="contact" method="post" app="perch_forms"> <perch:cont ...

"Is there a way to alter the background color of the second span within a Bootstrap row

I currently have 4 WordPress services in a loop, and I am trying to change the background color of the second service. However, when I try to apply the CSS background property, it ends up affecting all of the services. Here is my template code: <div ...