Establishing the size of the <img> alternative for <source> within <picture> to enhance SEO and optimize page loading speed

In the following code snippet, I am aiming to achieve the following:

  • Allowing the browser to choose between WEBP <source> and JPEG in<img> (as a fallback).
  • Displaying the image at 754px width for viewport widths greater than 1058px. For smaller viewports, automatically selecting one of the five images provided and stretching it to the viewport width.
  • The src attribute of the <img> should point to a low-resolution lazy load version of the image.
  • Specifying the width and height of the image in HTML for SEO/UX purposes (more details below).

    <div>
    <picture>
    <source type="image/webp" 
         data-srcset="
            image_100.webp 100w, 
            image_200.webp 200w, 
            image_400.webp 400w, 
            image_600.webp 600w,
            image_754.webp 754w" 
            data-sizes="(min-width: 1058px) 1000px, 100%" />
    <img data-srcset="
            image_100.png 100w, 
    		image_200.png 200w, 
    		image_400.png 400w, 
    		image_600.png 600w,
    		image_754.png 754w"
    		data-sizes="(min-width: 1058px) 1000px, 100%"
    		src="image_min.png" width="1000" height="300" alt="image_alt" />
    </picture>
    </div>
    

You may be wondering why there are data- prefixes. This is because I intend to use a lazy loading script that will remove them at the optimal time when the image needs to be displayed.

Prior to the activation of the lazy loading script, the browser will disregard the <source> element since proper srcset and sizes will not be present. Similarly, the browser will ignore the data-srcset and data-sizes attributes of the <img>, opting to display a low-resolution or placeholder image as specified in the src.

In terms of image dimensions and aspect ratio, I also want to include these values in the HTML markup so the browser can allocate the necessary space for the image during the loading process, thus avoiding unnecessary re-rendering.

Solely defining absolute image values within the style or through the width and height attributes of the <img> is applicable only for viewport widths exceeding 1058px. In other cases, the dimensions are relative to the viewport size. Therefore, I wish to inform the browser that the image will occupy 100% width and 30% height in relation to the parent <div>, which would hold true across different scenarios.

Though aware of the css padding-top technique to maintain an aspect ratio of a div, I have reservations about applying this method in the current context due to the additional padding created above the image.

Any alternative suggestions for determining the dimensions of the fallback image?

Answer №1

If you're looking for a solution, consider wrapping the <picture> element within a <div> container and utilizing CSS to maintain its aspect ratio by including the padding-top hack:

<div style="position:relative;" width:100%; padding-top:33%>
<picture>
<source type="image/webp" 
     srcset="
        image_100.webp 100w, 
        image_200.webp 200w, 
        image_400.webp 400w, 
        image_600.webp 600w,
        image_754.webp 754w" 
        sizes="(min-width: 1058px) 1000px, 100%" />
<img srcset="
        image_100.png 100w, 
        image_200.png 200w, 
        image_400.png 400w, 
        image_600.png 600w,
        image_754.png 754w" 
        sizes="(min-width: 1058px) 1000px, 100%" 
        src="image_min.png" style="width:100%;height:100%;position:absolute" alt="image_alt" />
</picture>
</div>
  • The fallback <img> within the <div> should have its width and height set to 100%, with a position:absolute property.
  • The wrapper <div> needs to have a CSS property of position:relative so that the image can be positioned within it absolutely.
  • The <div> should have its width and padding-top adjusted to match the dimensions/aspect ratio of the image.
  • The CSS styling doesn't necessarily have to be inline so that different viewport sizes can be accommodated using media queries.

Here's how it functions:

The <img> element fills up the entire <div> component. With position:absolute, the padding-top of the <div> doesn't influence the image's position. The percentage value of padding-top is related to the element's width, preserving the aspect ratio (e.g. setting padding-top to 100% would result in a consistently square wrapper).

The primary advantages for SEO/UX:

Regardless of the values in sizes and srcset, knowing the dimensions (and consequently the aspect ratio) allows us to generate a placeholder using CSS for the backup <img>, ensuring space reservation for an image not yet loaded or chosen from the srcset by the browser.

This approach ultimately prevents disruptive changes in page layout caused by images loading after the initial rendering of the page.

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

Basic Timer with Visual Background

Struggling to find the right CSS/script for a straightforward countdown timer, Here are the requirements: Countdown in days only, no need for hours, minutes, and seconds Ability to use a custom image as background I've scoured online searches but n ...

Conceal the div element if the value is either undefined or empty in AngularJS

I am experiencing an issue where I get 2 different values when I use console.log($scope.variable). The values shown are undefined and ''. Based on this value, I need to hide a div. Here's what I have tried: <div ng-hide="$scope.variable ...

Returning a button to its original state

Currently, I am working on styling the video controls on my website and have run into a small issue. The video section consists of a video list and a video player. When an li element from the list is clicked, the source of the video player changes to the ...

Decimal error causing Bootstrap grid column division issue

I've been attempting to divide the Bootstrap grid column into 20 grids using the code below: <div style="width: 4.999999998%; margin-top: -27.5px; margin-left: 25px;" class="col-md-.6 col-sm-6"> <div style="height: 32.5px; ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

What is the best way to distinguish the Footer from the Content?

While I was honing my skills in crafting a website using only HTML and CSS, I encountered an issue. I couldn't figure out how to place the footer beneath the content properly. My goal was to clearly separate each section - header, content, and footer. ...

Guide on integrating React with Node.js and HTML

I've tried various methods, searched on Google, and checked the official site, but nothing seems to work. The code only functions properly when I include it in the HTML file of node.js like this: <!DOCTYPE html> <html lang="en"& ...

Make sure to have the list available while choosing an item

I want to design a unique CSS element with the following characteristics: Include a button. When the button is clicked, a list of items (like a dropdown list) should appear. We should be able to select items by clicking on them, and the parent component s ...

Error in THREE.js: The function material.onBeforeRender is not defined

Can someone assist me with an error I'm encountering while trying to run my code in Three.js? The error message reads as follows: three.js:19528 Uncaught TypeError: material.onBeforeRender is not a function at renderObject (three.js:19528) at ...

The tabbing feature in bxslider disrupts the alignment of slides, making it

After encountering accessibility issues, I upgraded the bxslider library to version 4.2.3 for better support. Check out this example of bxslider where you can easily tab through the controls: http://jsfiddle.net/qax7w8vt/2/embedded/result/ The problem a ...

Ways to convert a PHP script to utilize PDO

Previously, a query was used to retrieve website settings stored in the database by an administrator, such as MyCompanyName or Copyright text. These settings were added in the site's backend by the admin. <?php error_reporting (E_ALL ^ E_NOTICE) ...

Issue with CSS Scroll Bar

I recently incorporated an Accordion and Slideshow feature into my website located at However, when clicking Play on either feature, a scroll bar unexpectedly appears causing the page to shift. I suspect that I may have forgotten to set the height for a ...

Revolutionary newspaper design utilizing asp.net's C# web forms

Trying to create a dynamic newspaper layout using ASP.NET C# web form. Struggling to set the page layout size inside a slider and display specific news content on a new page when clicking on an area of the newspaper using Repeater or another suitable contr ...

How to eliminate spacing between slides in a 3D Carousel Slider using Bootstrap 5

My website utilizes Bootstrap along with a carousel slider, which is functioning properly. However, I am encountering an issue when the slider transitions from right to left. It briefly displays a white space between slides, which I wish to eliminate. I wa ...

Prevent issues with text overlap in HTML and CSS

My text is overlapping when I resize the window. How can I prevent this? I want the text to resize only if it collides with other elements, or stack under each other if resizing is not possible. problem I've already attempted using flex box setting ...

Best practices for coding in HTML and CSS

Creating my first website for an internship has been quite a learning experience. Throughout my training, I was always advised to avoid embedding styles directly into the HTML code. However, now that I am actually developing a site, I can't help but f ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

Tips for relocating several buttons to the upper right corner

I have a dilemma with the positioning of 10 buttons on my webpage. Specifically, I would like to place them in the top right corner, but they are currently at the bottom. Can you assist me with moving the buttons? My desired outcome can be seen here. I s ...

Open a new window using the HTML <a> tag and pass POST values

I need to open a new window and send a POST value to a PHP file. For example: <a href='URL.php' target='_blank'> This is a link </a> How can I achieve sending a POST value? Edit: I have already tried the following method ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...