image-set()
image-set() CSS 函数式标记法是一种让浏览器从给定的一组CSS图像中选择最合适图像的方法,主要用于高像素密度屏幕。
设备和网络接入的分辨率和带宽各不相同。image-set() 函数为用户设备提供最合适的图像分辨率,通过提供一组图像选项——每个选项都带有一个相关的分辨率声明——浏览器从中选择最适合设备和设置的图像。分辨率可以作为文件大小的代理——连接慢、屏幕分辨率高的移动用户代理可能更倾向于接收较低分辨率的图像,而不是等待较高分辨率的图像加载。
image-set() 允许作者提供选项,而不是决定每个单独用户需要什么。
语法
css
/* Select image based on resolution */
image-set(
"image1.jpg" 1x,
"image2.jpg" 2x
);
image-set(
url("image1.jpg") 1x,
url("image2.jpg") 2x
);
/* Select gradient based on resolution */
image-set(
linear-gradient(blue, white) 1x,
linear-gradient(blue, green) 2x
);
/* Select image based on supported formats */
image-set(
url("image1.avif") type("image/avif"),
url("image2.jpg") type("image/jpeg")
);
值
<image>-
<image>可以是任何图像类型,但不能是图像集。image-set()函数不能嵌套在另一个image-set()函数中。 <string>-
指向图像的 URL。
<resolution>可选-
<resolution>单位包括x或dppx(每像素点数)、dpi(每英寸点数)和dpcm(每厘米点数)。image-set()中的每个图像必须具有唯一的分辨率。 type(<string>)可选-
有效的 MIME 类型字符串,例如 "image/jpeg"。
正式语法
<image-set()> =
image-set( <image-set-option># )
<image-set-option> =
[ <image> | <string> ] [ <resolution> || type( <string> ) ]?
<image> =
<url> |
<image()> |
<image-set()> |
<cross-fade()> |
<element()> |
<gradient>
<image()> =
image( <image-tags>? [ <image-src>? , <color>? ]! )
<cross-fade()> =
cross-fade( <cf-image># )
<element()> =
element( <id-selector> )
<image-tags> =
ltr |
rtl
<image-src> =
<url> |
<string>
<cf-image> =
[ <image> | <color> ] &&
<percentage [0,100]>?
<id-selector> =
<hash-token>
无障碍
浏览器不会向辅助技术提供任何有关背景图像的特殊信息。这对于屏幕阅读器来说尤其重要,因为屏幕阅读器不会播报背景图像的存在,因此也不会向其用户传达任何信息。如果图像包含对理解页面整体目的至关重要的信息,最好在文档中以语义化的方式对其进行描述。
示例
使用 image-set() 提供替代的 background-image 选项
此示例展示了如何使用 image-set() 提供两个替代的 background-image 选项,根据所需的分辨率进行选择:一个正常版本和一个高分辨率版本。
html
<div class="box"></div>
css
.box {
width: 400px;
height: 200px;
background-repeat: no-repeat;
background-size: cover;
background-image: image-set(
url("https://mdn.github.io/shared-assets/images/examples/balloons-small.jpg")
1x,
url("https://mdn.github.io/shared-assets/images/examples/balloons-landscape.jpg")
2x
);
}
使用 image-set() 提供替代图像格式
在下一个示例中,type() 函数用于以 AVIF 和 JPEG 格式提供图像。如果浏览器支持 avif,它将选择该版本。否则,它将使用 jpeg 版本。
html
<div class="box"></div>
css
.box {
width: 400px;
height: 200px;
background-repeat: no-repeat;
background-size: cover;
background-image: image-set(
"https://mdn.github.io/shared-assets/images/examples/balloons-landscape.avif"
type("image/avif"),
"https://mdn.github.io/shared-assets/images/examples/balloons-landscape.jpg"
type("image/jpeg")
);
}
规范
| 规范 |
|---|
| CSS 图像模块第 4 级 # image-set-notation |
浏览器兼容性
加载中…