Reference HTML reference

HTML picture 参考

<picture> 用于根据媒体条件或图片格式选择不同图片资源。它常见于响应式图片、WebP/AVIF 优先加载和移动端裁剪图。

语法

html
<picture>
  <source media="(max-width: 640px)" srcset="/images/banner-mobile.webp">
  <source type="image/avif" srcset="/images/banner.avif">
  <img src="/images/banner.webp" alt="课程封面">
</picture>

常用属性

元素或属性 说明
<source> 定义候选资源
media 媒体查询条件
type 图片 MIME 类型
srcset 候选图片地址
<img> 必须保留,作为最终回退内容

可运行演示

在线代码演示
源码
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>picture 响应式图片演示</title>
    <style>
      * { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #0f172a; background: #f8fafc; }
      .card { max-width: 760px; margin: 0 auto; overflow: hidden; border: 1px solid #dbeafe; border-radius: 12px; background: #fff; }
      img { display: block; width: 100%; height: auto; }
      p { margin: 0; padding: 14px 16px; color: #475569; }
    </style>
  </head>
  <body>
    <article class="card">
      <picture>
        <source media="(max-width: 560px)" srcset="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='640' height='420'%3E%3Crect width='640' height='420' fill='%23dbeafe'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' font-family='Arial' font-size='36' fill='%231e3a8a'%3EMobile image%3C/text%3E%3C/svg%3E">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='960' height='360'%3E%3Crect width='960' height='360' fill='%23bfdbfe'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' font-family='Arial' font-size='44' fill='%231e40af'%3EDesktop image%3C/text%3E%3C/svg%3E" alt="响应式图片占位示例">
      </picture>
      <p>缩小预览区域时,picture 会切换到移动端图片。</p>
    </article>
  </body>
</html>

常见错误

  • 只写 <source> 不写 <img>,导致没有回退内容。
  • 把 alt 写在 <source> 上;替代文本应写在 <img>。
  • media 条件重叠时顺序不清晰,浏览器会使用第一个匹配资源。
  • 为同一图片提供过多候选,增加维护成本。

相关内容