HTML <picture> 标签用于显示不同尺寸的显示器和设备的图像。这是 <img> 标签的替代标签。它包含 <source> 和 <img> 标签。
一个或多个 <source> 标签和一个或多个 <img> 标签(充当块的最后一个子元素)包含在 <picture> 标签中。
<source> 元素中包含各种显示设备方案的图像版本。图像的大小和其他属性在 <img> 元素中进行了描述。
<picture> 元素允许指定多个图像,以便更准确地填充浏览器视口,而不是根据视口宽度缩放一个图像。
- 针对各种媒体情况调整和裁剪图片
- 在不支持特定格式时提供替代图像格式。
语法
<picture> ... </picture>
属性
<picture> 标签支持 HTML 的 全局属性 和 事件属性。
<picture> 标签示例
以下示例将说明<picture> 标签的用法。在哪里、何时以及如何使用<picture> 标签,以及我们如何使用 CSS 操作<picture> 标签。
创建<picture> 标签
让我们看一下以下示例,我们将在其中使用基本的 <picture> 标签。
<!DOCTYPE html>
<html>
<style>
body {
text-align: center;
}
</style>
<body style="background-color:#EAFAF1">
<picture>
<source media="(min-width: 600px)"
srcset="/artificial_intelligence/images/artificial-intelligence-mini-logo.jpg">
<source media="(min-width: 450px)"
srcset=
"/cg/images/logo.png">
<img src=
"/html/images/html-mini-logo.jpg"
alt="LOGO" style="width:auto;">
</picture>
</body>
</html>
<picture> 使用 Media 属性增强图像
考虑到另一种情况,我们将使用 media 属性和 <picture> 标签,在这种情况下,我们将获取两个图像源并检查浏览器显示哪一个。
<!DOCTYPE html>
<html>
<body style="background-color:#E8DAEF">
<picture>
<source media="(max-width: 60px)"
srcset="https://upload.wikimedia.org/wikipedia/en/thumb/4/41/Flag_of_India.svg/300px-Flag_of_India.svg.png" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/CK_Nayudu_1930s.jpg/225px-CK_Nayudu_1930s.jpg" alt="ck nayudu" />
</picture>
</body>
</html>
<picture> 使用 srcset 实现响应式图像
按照示例,我们将使用 srcset 属性和 <picture> 标签。
<!DOCTYPE html>
<html>
<body style="background-color:#EBF5FB">
<picture>
<source media="(min-width:650px)"
srcset=
"https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/The_forest_near_Blatets%2C_Vinitsa.JPG/330px-The_forest_near_Blatets%2C_Vinitsa.JPG" />
<source media="(min-width:465px)"
srcset="https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Cat_yawn_with_exposed_teeth_and_claws.jpg/330px-Cat_yawn_with_exposed_teeth_and_claws.jpg" width="1000px" height="200px" />
<img src=
"https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/S%C3%A4ugende_H%C3%BCndin.JPG/330px-S%C3%A4ugende_H%C3%BCndin.JPG" alt="dog" style="width:auto;" />
</picture>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
<picture> | 38.0 | 13.0 | 38.0 | 9.1 | 25.0 |