12

I know the solution is <picture>

but which format is standard?

1.

 <picture>
   <source type="image/webp" srcset="pic.webp">
   <img src="pic.jpg"  alt="test">
 </picture>

2.

 <picture>
   <source type="image/webp" srcset="pic.webp">
   <img src="pic.jpg"  alt="test" type="image/jpeg">
 </picture>

3.

 <picture>
   <source type="image/webp" srcset="pic.webp">
   <source type="image/jpeg" srcset="pic.jpg">
   <img src="pic.jpg"  alt="test">
 </picture>

1 Answer 1

13

Number 1 would be the standard way of doing it.

When using the <picture> element the browser looks through each <source> element – starting from the top – to find an image that best fits the the current scenario. In your case it would only be if it supports the format in the type attribute. But it could also look for things like media queries in the media attribute or the pixel density of the user's screen if you add 2x or 3x versions in the srcset list.

As stated on MDN, if the browser can't find a fitting match in the <source>s, it defaults to the <img> tag:

The <img> element serves two purposes:

It describes the size and other attributes of the image and its presentation. It provides a fallback in case none of the offered <source> elements are able to provide a usable image.

So the JPEG in your example doesn't need to have a <source> as well, because it will be chosen if none of the <source>s are used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.