2

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):

Normal

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.

Stretched

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 heightassociated with that` element?

Any ideas greatly appreciated.

Myles Gray
  • 8,711
  • 7
  • 48
  • 70

1 Answers1

0

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>.

Andris Jefimovs
  • 689
  • 6
  • 17
  • Hm, judging by that though I could use the `sizes` param on that element? The challenge is that this is a Hugo theme I've built and I want it to be able to accept a width and heigh defined by the user in the config file, hence the `width` and `height` being defined in HTML. I'll play with `sizes` and see if that helps. – Myles Gray Nov 13 '21 at 14:55
  • It also appears that Safari <15 has no support for the `source` element anyway, so CSS it is I support. https://caniuse.com/?search=source – Myles Gray Nov 13 '21 at 15:01
  • Further investigate: all browsers on iOS _must_ use webkit because of Apple's restrictions, so that explains why all iOS browsers on – Myles Gray Nov 13 '21 at 16:25