概述
作用:起到和 img 标签的 srcset 属性 相似的作用;
picture
元素就像是图像和其源的容器。浏览器仍然需要 img 元素,用来表明需要加载的图片
优点:使用 picture 元素选择图像,不会有歧义;(逻辑更清晰)
语法
结构:picture 元素 包含 0 或 n 个 source 元素 和 1 个 img 元素; --> 为不同的 显示/设备场景提供图像版本;
示例:见下方;
规则
- 浏览器会**
选择最匹配的
**⼦ source 元素; - 如果没有匹配的就选择 img 元素的 src 的 url;
- 最后,所选元素呈现在 img 元素占据的空间中;
标签:
picture 包裹的容器;
source
- media 属性:媒体查询条件;
- srcset 属性:指向符合媒体查询的媒体文件;
示例
<picture>
<!-- 大于640px 的尺寸,选择 640.png -->
<source srcset="640.png" media="(min-width: 640px)" />
<!-- 大于 480px的尺寸,选择 480png -->
<source srcset="480.png" media="(min-width: 480px)" />
<!-- 大于320.png 选择 img 标签指向的 320.png -->
<img src="320.png" alt="" />
</picture>
<picture>
<source srcset="/media/examples/surfer-240-200.jpg" media="(min-width: 800px)" />
<img src="/media/examples/painted-hand-298-332.jpg" />
</picture>