HTML <picture>
元素通过包含零或多个 {{HTMLElement("source")}} 元素和一个 {{HTMLElement("img")}} 元素来为不同的显示/设备场景提供图像版本。浏览器会选择最匹配的子 <source>
元素,如果没有匹配的,就选择 <img>
元素的 {{htmlattrxref("src", "img")}} 属性中的URL。然后,所选图像呈现在<img>元素占据的空间中。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
要决定加载哪个URL,{{Glossary("user agent")}} 检查每个 <source>
的 {{htmlattrxref("srcset", "source")}}、{{htmlattrxref("media", "source")}} 和 {{htmlattrxref("type", "source")}} 属性,来选择最匹配页面当前布局、显示设备特征等的兼容图像。
<picture>
的常见使用场景:
media
条件裁剪或修改图像If providing higher-density versions of an image for high-DPI (Retina) display, use {{htmlattrxref("srcset", "img")}} on the <img>
element instead. This lets browsers opt for lower-density versions in data-saving modes, and you don't have to write explicit media
conditions.
内容分类 | 流内容,表述内容,嵌入内容。 |
---|---|
允许的内容 | 零或多个 {{HTMLElement("source")}} 元素,以及紧随其后的一个 {{HTMLElement("img")}} 元素,可以混合一些脚本支持的元素。 |
标签省略 | {{no_tag_omission}} |
允许的父元素 | 任何可以包含嵌入内容的元素。 |
允许的 ARIA roles | 无 |
DOM 接口 | {{domxref("HTMLPictureElement")}} |
这个元素只包含全局属性。
你可以使用 {{cssxref("object-position")}} 属性调整元素框架内图像的位置,用 {{cssxref("object-fit")}} 属性控制图片如何调整大小来适应框架。
提示:在子 <img>
元素上使用这些属性,不是 <picture>
元素。
这些示例演示了 {{HTMLElement("source")}} 元素的不同属性如何更改<picture>
中图像的选择。
media
属性media
属性允许你提供一个用于给用户代理作为选择 {{HTMLElement("source")}} 元素的依据的媒体条件(media condition)(类似于媒体查询)。如果这个媒体条件匹配结果为 false
,那么这个 {{HTMLElement("source")}} 元素会被跳过。
<picture> <source srcset="mdn-logo-wide.png" media="(min-width: 600px)"> <img src="mdn-logo-narrow.png" alt="MDN"> </picture>
type
属性type
属性允许你为 {{HTMLElement("source")}} 元素的 srcset
属性指向的资源指定一个 MIME 类型。如果用户代理不支持指定的类型,那么这个 {{HTMLElement("source")}} 元素会被跳过。
<picture> <source srcset="mdn-logo.svg" type="image/svg+xml"> <img src="mdn-logo.png" alt="MDN"> </picture>
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('HTML WHATWG', 'embedded-content.html#the-picture-element', '<picture>')}} | {{Spec2('HTML WHATWG')}} | 初始定义 |
{{Compat("html.elements.picture")}}