I can't seem to discern a difference in function or meaning between using the picture
element or just using the img
element with the srcset
attribute. I understand how they work; I just don't fully understand why or when to choose one over the other.
It looks like img
element is lighter, cleaner code, but does it mean and do the same thing? I'm using this in my code to serve up different scaled versions of the same image:
<img src="default.jpg"
srcset="image-800.jpg 800w, image-400.jpg 400w, image-200.jpg 200w"
sizes="(max-width: 800px) 100vw, 12em"
alt="something" />
It does exactly what I want as far as serving up the correct scaled image and it seems to work in Chrome, Firefox, Edge, and Opera.
I know that pretty much the same thing can be done with this code:
<picture>
<source srcset="image-800.jpg 800w, image-400.jpg 400w, image-200.jpg 200w"
media="(max-width: 800px)"
sizes="100vw" />
<source srcset="image-800.jpg 800w, image-400.jpg 400w, image-200.jpg 200w"
media="(min-width: 800px)"
sizes="12em" />
<img src="default.jpg" alt="something" />
</picture>
So, what's the difference functionally? Why would I use more code to do essentially the same thing?
Is there a semantic difference? What would that be?
From w3.org img
:
An
img
element represents an image and its fallback content.
Also from w3.org picture
:
The
picture
element is a container which provides multiples sources to its contained img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors. It represents its children.
If the srcset
attribute already does this for the img
element, why do we need a picture
element as a container? What am I missing? Is there a difference in semantic meaning?
I read one other post on here with a comment that suggested that srcset
on the img
element was simply new and not completely reliable crossbrowser. Is that still true? Was that the only difference?
<picture>
is to allow images with different formats instead of just different sizes, à la<video>
/<audio>
. You could prefer to serve a slightly smaller WebP on Chrome and fall back on a different format for other browsers, for example. In the future, there should be more and better formats, supported by more browsers. – Ry-<img srcset>
when not serving different formats. And… it should be okay to reply to comments like that, but I didn’t get a notification this time for some reason. Weird. – Ry-