CSS 函式 - image-set()



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"。

對於 Chrome 和 Safari,應使用字首 -webkit。建議使用字首版本以確保瀏覽器完全相容。

輔助功能問題:沒有向輔助技術提供有關背景影像的特殊資訊,因此螢幕閱讀器也不會宣佈有關背景影像的任何內容。如果此類背景影像很重要並且向用戶傳達了任何資訊,輔助技術將無法識別。建議在文件中以語義方式描述此類資訊。

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-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>
廣告

© . All rights reserved.