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 |
瀏覽器相容性
載入中…