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
andheight
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?