@media是CSS中用于响应式设计的媒体查询规则,可根据屏幕宽度、高度、方向等特性动态应用不同样式,如@media(max-width:600px){p{color:red;}}实现小屏文字变红。

按屏幕尺寸 + 格式双维度适配的写法
你可以为同一尺寸区间提供多个
<picture><!-- 桌面端:优先 WebP,降级到 AVIF,最后 JPEG --><source media="(min-width: 1200px)" srcset="hero-desktop.webp" type="image/webp"><source media="(min-width: 1200px)" srcset="hero-desktop.avif" type="image/avif"><source media="(min-width: 1200px)" srcset="hero-desktop.jpg" type="image/jpeg"><!-- 平板端:同理 --><source media="(min-width: 768px) and (max-width: 1199px)" srcset="hero-tablet.webp" type="image/webp"><source media="(min-width: 768px) and (max-width: 1199px)" srcset="hero-tablet.avif" type="image/avif"><source media="(min-width: 768px) and (max-width: 1199px)" srcset="hero-tablet.jpg" type="image/jpeg"><!-- 手机端:小图 + 格式降级 --><source media="(max-width: 767px)" srcset="hero-mobile.webp" type="image/webp"><source media="(max-width: 767px)" srcset="hero-mobile.avif" type="image/avif"><source media="(max-width: 767px)" srcset="hero-mobile.jpg" type="image/jpeg"><!-- 最终兜底:无 media、无 type,所有浏览器都认 --> @@##@@ </source></source></source></source></source></source></source></source></source></picture>
- 浏览器会从上到下逐个检查
- 先看
media是否匹配当前视口(比如宽度),再看type是否被当前浏览器支持 - 一旦某条
的media匹配且type可用,就立即加载它的srcset,不再往后看 - 所有
都不命中时,才加载的
src
更紧凑的写法(推荐日常使用)
多数项目只需兼顾 WebP 和 JPEG,可简化结构,减少冗余:
<picture><source media="(min-width: 900px)" srcset="banner-lg.webp" type="image/webp"><source media="(min-width: 900px)" srcset="banner-lg.jpg" type="image/jpeg"><source media="(max-width: 899px)" srcset="banner-sm.webp" type="image/webp"><source media="(max-width: 899px)" srcset="banner-sm.jpg" type="image/jpeg"> @@##@@ </source></source></source></source></picture>
- 四个
覆盖两个尺寸段 × 两种格式 - 不需要为每个尺寸写三套,WebP 支持率已超 98%(Chrome/Firefox/Safari 14+ / Edge),AVIF 可按需添加
验证是否生效的小技巧
- 在 Chrome DevTools → Network 面板刷新页面,筛选
Img类型,看加载的是.webp还是.jpg - 切换设备模拟器(如 iPhone SE / iPad Pro),观察不同宽度下请求的文件名变化
- 在 Firefox 或旧版 Safari 中打开,确认回退到 JPEG
注意: 的 type 属性只校验 MIME 类型是否被浏览器声明支持,不校验文件内容;确保服务器对 .webp 和 .avif 返回正确的 Content-Type 响应头(如 image/webp),否则可能被忽略。

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











