<img srcset="..."/> versus <picture><source/>?

时间:2018-09-18 19:30:38

标签: html5 image semantic-markup responsive-images srcset

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?

2 个答案:

答案 0 :(得分:1)

在您的示例中,<picture>是无用的,因为您想在各处显示相同的图像内容。

<picture>是强制性的,例如当您遇到断点时更改图像的宽度/高度比,或者在小型设备上裁剪图像以放大时。

Id是强制性的。 / p>

答案 1 :(得分:1)

沿美术指导,使用<picture>的用例是要提供其他文件类型时。例如,Chrome支持webp的压缩比JPG更好。让Chrome选择webp文件的唯一方法是通过<picture>提供。

<picture>
    <source srcset="image-800.webp 800w, image-400.webp 400w, image-200.webp 200w" 
type='image/webp' media="(max-width: 800px)" 
sizes="100vw" />
    <img src="default.webp" alt="something" />
</picture>