網頁功能:
image-set()
在 CSS 虛擬元素 (例如 ::before 或 ::after) 中使用解析度最佳化的圖片,即可加入裝飾圖示或結構圖形,不必在 HTML 中加入額外的 DOM 節點。只要將虛擬元素與 image-set() CSS 函式結合,就能為瀏覽器提供多種格式 (例如 AVIF 或 WebP) 和解析度 (例如 1x 和 2x)。瀏覽器會根據使用者的裝置功能,自動選擇最合適的圖片。
導入作業
您可以直接在虛擬元素的 content 屬性或 background-image 屬性 (設定 content: "" 時) 中使用 image-set() 函式。請注意,雖然同時透過 type() 提供圖片格式和解析度 (例如 1x 或 2x) 可獲得最佳效果,但這兩個引數都是選用的。
.icon-button::before {
/* Using image-set directly in the content property */
/* MANDATORY: Always order your formats from most optimized (AVIF) to least optimized (JPEG/PNG).
The browser will stop at the first supported format. */
content: image-set(
url("icon.avif") type("image/avif") 1x,
url("icon-2x.avif") type("image/avif") 2x,
url("icon.webp") type("image/webp") 1x,
url("icon-2x.webp") type("image/webp") 2x,
url("icon.png") type("image/png") 1x,
url("icon-2x.png") type("image/png") 2x
);
display: inline-block;
margin-right: 8px;
vertical-align: middle;
}
備用策略
如果舊版瀏覽器不支援 image-set() 函式,您「必須」在 image-set() 規則「之前」提供標準圖片宣告。這項漸進增強策略仰賴 CSS 的階層特性:系統會忽略不支援的規則。
.icon-button::before {
/* MANDATORY: Fallback for browsers that do not support image-set() */
content: url("icon.png");
/* Modern browsers will apply this and override the fallback */
content: image-set(
url("icon.avif") type("image/avif") 1x,
url("icon-2x.avif") type("image/avif") 2x,
url("icon.png") type("image/png") 1x,
url("icon-2x.png") type("image/png") 2x
);
}