HTML gives us the picture
tag, which does a very similar job of the srcset
attribute of an img
tag, and the differences are very subtle.
HTML为我们提供了picture
标签,它与img
标签的srcset
属性非常相似,并且区别非常细微。
You use picture
when instead of just serving a smaller version of a file, you completely want to change it. Or serve a different image format.
当您完全希望更改文件时,而不是仅提供较小版本的文件时,便使用picture
。 或提供其他图像格式。
The best use case I found is when serving a WebP image, which is a format still not widely supported. In the picture
tag you specify a list of images, and they will be used in order, so in the next example, browsers that support WebP will use the first image, and fallback to JPG if not:
我发现的最佳用例是在提供WebP图像时,该图像仍未被广泛支持。 在picture
标签中,您指定了图像列表,这些图像将按顺序使用,因此在下一个示例中,支持WebP的浏览器将使用第一个图像,如果不使用,则回退为JPG:
<picture>
<source type="image/webp" srcset="image.webp">
<img src="image.jpg" alt="An image">
</picture>
The
source
tag defines one (or more) formats for the images. Theimg
tag is the fallback in case the browser is very old and does not support thepicture
tag.
source
标签为图像定义一种(或多种)格式。img
标签是备用浏览器,如果浏览器很旧并且不支持picture
标签。
In the source
tag inside picture
you can add a media
attribute to set media queries.
在picture
内的source
标签中,您可以添加media
属性以设置媒体查询。
The example that follows kind of works like the above example with srcset
:
下面的示例类似于srcset
的上述示例:
<picture>
<source media="(min-width: 500w)" srcset="dog-500.png" sizes="100vw">
<source media="(min-width: 800w)" srcset="dog-800.png" sizes="100vw">
<source media="(min-width: 1000w)" srcset="dog-1000.png" sizes="800px">
<source media="(min-width: 1400w)" srcset="dog-1400.png" sizes="800px">
<img src="dog.png" alt="A dog image">
</picture>
But that’s not its use case, because as you can see it’s much more verbose.
但这不是用例,因为如您所见,它更加冗长。
The picture
tag is recent but is now supported by all the major browsers except Opera Mini and IE (all versions).
picture
标签是最新的,但除Opera Mini和IE(所有版本)外,所有主流浏览器现在都支持它 。