CSS 中的 image-set() 函数让浏览器从给定的集合中选择最合适的图像,主要用于高像素密度的屏幕。
浏览器将根据设备的显示特性选择最合适的图像。如果设备具有更高的像素密度,它将选择具有较高像素密度的图像(如果可用)。移动连接速度较慢的同一设备更愿意接收低分辨率图像,而不是等待高分辨率图像或根本不加载任何图像。
函数 image-set() 允许用户为图像提供选项,而不是修复一个选项。
语法
<image-set()> = image-set( <image-set-option># )
一些示例语法如下:
image-set(
"sampleimage1.png" 1x,
"sampleimage2.png" 2x
);
image-set(
url("sampleimage1.png") 1x,
url("sampleimage2.png") 2x
);
/* use of gradient as image */
image-set(
linear-gradient(red, yellow) 1x,
linear-gradient(green, yellow) 2x
);
/* use of supported formats of images */
image-set(
url("sampleimage1.png") type("sampleimage.png"),
url("sampleimage2.jpg") type("sampleimage2.jpeg")
);
在上述语法中:
- url(“sampleimage1.png”) 1x 表示像素密度为 1x 的第一个图像源。
- url(“sampleimage2.png”) 2x 表示像素密度为 2x 的第二个图像源。
可能的值
image-set() 函数可以包含以下值:- <image>:可以是除图像集以外的任何图像类型,这意味着函数 image-set() 不能嵌套在另一个 image-set() 函数中。
- <string>:列出图像的 URL。
- <resolution>:可选,指定图像的分辨率,以各种单位表示,例如:
- X, DPPX:表示每像素单位的点数。
- DPI:表示每英寸点数单位。
- DPCM:每厘米点数单位。
- type(<string>):可选并指定有效的 MIME 类型字符串,如“sampleimage.jpeg”。
前缀 -webkit 应用于 Chrome 和 Safari。建议使用前缀版本,以实现浏览器的完全兼容性。
可访问性问题:没有向辅助技术提供有关背景图像的特殊信息,因此屏幕阅读器中也不会公布有关背景图像的任何内容。如果这样的背景图像很重要并且意味着对用户的任何信息,那么辅助技术就会错过。建议在文档中对此类信息进行语义描述。
可访问性问题:没有向辅助技术提供有关背景图像的特殊信息,因此屏幕阅读器中也不会公布有关背景图像的任何内容。如果这样的背景图像很重要并且意味着对用户的任何信息,那么辅助技术就会错过。建议在文档中对此类信息进行语义描述。
CSS image-set() - 替代背景图片
以下示例演示了如何使用 image-set() 函数来设置备用背景图像:
<html>
<head>
<style>
.box {
background-image: -webkit-image-set(
"images/border.png" 1x,
"images/white-flower.jpg" 2x
);
background-image: image-set(
"images/border.png" 1x,
"images/white-flower.jpg" 2x
);
border: 3px solid black;
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
CSS image-set() - 替代图像格式
以下示例演示了如何使用 image-set() 函数为背景图像指定替代图像格式:
<html>
<head>
<style>
.box {
background-image: -webkit-image-set(
"images/red-flower.jpg" 1x,
"images/border.png" 2x
);
background-image: image-set(
"images/red-flower.jpg" 1x,
"images/border.png" 2x
);
border: 3px solid black;
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
CSS image-set() - 提供后备选项
如果任何浏览器都不支持 image-set() 函数,您可以提供一个回退选项 image 作为背景。您需要在使用 image-set() 函数的行之前进行单独的声明,因为该函数没有内置的回退选项。
<html>
<head>
<style>
.box {
/* adding a fallback option*/
background-image: url("images/white-flower.jpg")
background-image: -webkit-image-set(
"images/red-flower.jpg" 1x,
"images/border.png" 2x
);
background-image: image-set(
"images/red-flower.jpg" 1x,
"images/border.png" 2x
);
border: 3px solid black;
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>