简体   繁体   中英

Responsive images: Picture element using width and height of fallback <img> tag when using AVIF/WEBP

I have a website that I have made responsive and utilise the <picture> element to serve up webp, avif and have a png fallback for older browsers. It should look like this (Chrome/Safari):

普通的

For some reason, certain browsers (Firefox 94 on desktop and mobile, Safari on iOS 14< as examples) will load the AVIF format of the image, but will use the explicit width and height from the fallback <img> tag I have inside the <picture> element, resulting in a warped image.

拉伸

The site in question is: https://blah.cloud/now (pull the browser to <768px wide to see the problem).

The code I'm doing the image selection with is as below:

<picture>
<source media="(min-width: 768px)" srcset="/images/logo-title.avif" type="image/avif" alt="logo" width="245" height="34">
<source media="(min-width: 768px)" srcset="/images/logo-title.webp" type="image/webp" alt="logo" width="245" height="34">
<source srcset="/images/logo.avif" type="image/avif" alt="logo" width="65" height="65">
<source srcset="/images/logo.webp" type="image/webp" alt="logo" width="65" height="65">
<img src="/images/logo-title.png" alt="logo" aria-label="logo" width="245" height="34">
</picture>

The reason for the explicit width and height is for Google PSI to avoid CLS.

I'm kind of at a loss here as to why this behaviour happens - if it is pulling the avif/webp image, and I've confirmed that it is, it should use the width and height associated with that ` element?

Any ideas greatly appreciated.

Unfortunately there is no width and height attribute for a <source> element! [ MDN ]

You could resize your image resources instead. Then make the <picture> element a block element and resize it in CSS. To adjust the image do object-fit: cover; (or other possible options you can find on MDN ) on <img> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM