分辨率优化伪元素

Web 功能: image-set()

在 CSS 伪元素(如 ::before 或 ::after)中使用分辨率经过优化的图片,可让您添加装饰性图标或结构性图形,而不会因额外的 DOM 节点而使 HTML 变得杂乱。通过将伪元素与 image-set() CSS 函数结合使用,您可以为浏览器提供多种格式(例如 AVIF 或 WebP)和分辨率(例如 1x 和 2x)。浏览器会自动选择最适合用户设备功能的图片。

实现

您可以直接在伪元素的 content 属性中使用 image-set() 函数,也可以在其 background-image 属性中使用该函数(同时设置 content: "")。请注意,虽然同时通过 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
  );
}