概述
`image-set()` 允许按设备像素密度(`1x/2x` 或 `1dppx/2dppx`)声明多版本图片,浏览器根据 DPR 选择最合适的资源。常用于 `background-image` 的响应式适配,与 ``/`srcset` 互补。
用法与示例
```css
.hero {
background-image: image-set(
url('/img/hero.avif') type('image/avif') 1x,
url('/img/[email protected]') type('image/avif') 2x
);
}
/* 也可用于 content 图像 */
.logo { content: url('/img/logo.webp'); content: image-set(url('/img/logo.webp') 1x, url('/img/[email protected]') 2x) }
```
工程建议
- MIME 与兼容:声明 `type()` 以提升选择准确性;对不支持 AVIF/WebP 的浏览器回退到 JPEG/PNG。
- 与尺寸占位:确保元素有固定尺寸或 `aspect-ratio`,避免布局抖动。
- 与缓存:在 CDN/服务器为变体设置正确 `Content-Type` 与缓存键;控制资源体积。
参考与验证
- MDN `image-set()` 文档:https://developer.mozilla.org/docs/Web/CSS/image-set
- CSS Images 规范:https://www.w3.org/TR/css-images-4/
- web.dev 响应式图片与背景指南:https://web.dev/articles/responsive-images
发表评论 取消回复