前置知识: HTML5

图像与响应式图片

1 minIntermediate2026/6/14

img、srcset、sizes、picture元素

1. img 元素

<img src="photo.jpg" alt="描述文字" width="800" height="600" />
<img src="photo.jpg" alt="照片" loading="lazy" />

2. 响应式

2.1 srcset 属性

<!-- 宽度描述符 -->
<img src="small.jpg" srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w" alt="响应式图片" />

<!-- 像素密度描述符 -->
<img src="photo.jpg" srcset="photo.jpg 1x, photo@2x.jpg 2x" alt="高分辨率图片" />

2.2 sizes 属性

<img
  src="photo.jpg"
  srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
  sizes="(max-width: 600px) 100vw, 50vw"
  alt="响应式图片"
/>

计算过程:选择宽度=sizes 计算值×设备像素比\text{选择宽度} = \text{sizes 计算值} \times \text{设备像素比}

2.3 picture 元素

<picture>
  <source srcset="photo.avif" type="image/avif" />
  <source srcset="photo.webp" type="image/webp" />
  <img src="photo.jpg" alt="照片" width="800" height="600" />
</picture>

3. 片格式选择

格式压缩透明度压缩率浏览器支持
JPEG有损中等全部
PNG无损较低全部
WebP有损/无损97%+
AVIF有损/无损最高92%+
SVG矢量全部

4. 片性能优化

<img src="photo.jpg" alt="照片" width="800" height="600" style="width: 100%; height: auto;" />
<link rel="preload" as="image" href="hero.webp" type="image/webp" />