해상도 최적화 의사 요소

웹 기능: image-set()

CSS 가상 요소 (예: ::before 또는 ::after)에 해상도 최적화 이미지를 사용하면 추가 DOM 노드로 HTML을 복잡하게 만들지 않고도 장식 아이콘이나 구조적 그래픽을 추가할 수 있습니다. 의사 요소를 image-set() CSS 함수와 결합하면 브라우저에 여러 형식 (예: AVIF 또는 WebP)과 해상도 (예: 1x 및 2x)를 제공할 수 있습니다. 브라우저는 사용자의 기기 기능에 가장 적합한 이미지를 자동으로 선택합니다.

구현

image-set() 함수는 가상 요소의 content 속성 내에서 직접 사용하거나 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() 규칙 앞에 표준 이미지 선언을 제공해야 합니다(MUST). 이 점진적 개선 전략은 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
  );
}