복잡한 도형

웹 기능: 마스크 SVG

개요

브러시 스트로크나 유기적 질감과 같은 복잡한 자유 형식 모양으로 요소를 클리핑하려면 CSS 마스킹 (mask-image)을 사용하세요. clip-path는 기하학적 모양이나 벡터 경로에 적합하지만, mask-image를 사용하면 이미지 (예: 투명도가 있는 PNG) 또는 SVG를 사용하여 요소의 표시 영역을 정의할 수 있습니다. 이 접근 방식은 반투명을 지원하므로 clip-path로는 구현하기 어렵거나 불가능한 부드러운 가장자리와 복잡한 질감을 표현할 수 있어 더 표현력이 뛰어납니다.

구현

CSS 마스크를 사용하여 복잡한 도형을 구현하려면 다음 단계를 따르세요.

이미지의 투명도 사용

이미지의 투명도를 마스크로 사용하여 불투명한 부분은 표시하고 투명한 부분은 숨길 수 있습니다. 이는 PNG, SVG 또는 투명도가 있는 다른 이미지이거나 CSS 그라데이션과 같이 생성된 이미지일 수 있습니다.

.shaped-element {
  /* MANDATORY: Use vendor prefix for wider support in older browsers */
  -webkit-mask-image: url('mask.svg');
  -webkit-mask-size: cover; /* Scale mask to cover element */
  -webkit-mask-repeat: no-repeat; /* Do not tile the mask */

  /* Standard property for modern browsers */
  mask-image: url('mask.svg');
  mask-size: cover;
  mask-repeat: no-repeat;
}

HTML에서 SVG 요소 사용

페이지의 HTML에서 인라인 SVG에 정의된 <mask> 요소를 참조할 수도 있습니다. maskContentUnits="objectBoundingBox"를 사용하여 요소 크기에 따라 마스크 크기가 자동으로 조정되도록 합니다. 이렇게 하면 브라우저가 마스크 내의 모든 좌표를 절대 픽셀이 아닌 0에서 1 사이의 분수(예: 50%의 경우 0.5)로 해석합니다.

휘도와 알파 마스킹: 기본적으로 SVG 마스크는 휘도 (밝기)를 사용하여 불투명도를 결정합니다. 흰색은 표시하고 검은색은 숨기며 회색은 반투명을 만듭니다. 마스크가 SVG 도형의 알파 채널 (투명도)을 사용하도록 하려면 CSS에서 mask-type: alpha;를 지정하거나 SVG <mask> 요소에 직접 mask-type="alpha"를 지정하면 됩니다.

<!-- White areas reveal content, gray creates semi-transparency, black or transparent hides it -->
<svg width="0" height="0">
  <defs>
    <!-- objectBoundingBox scales mask coordinates (0 to 1) with the element's size -->
    <mask id="custom-shape" maskContentUnits="objectBoundingBox">
      <!-- Use white shapes to define fully opaque areas -->
      <circle cx="0.5" cy="0.5" r="0.5" fill="white" />
      <!-- Use gray shapes to define semi-transparent/faded areas -->
      <circle cx="0.5" cy="0.5" r="0.25" fill="gray" />
    </mask>
  </defs>
</svg>

<div class="masked-content">
  <!-- Content to be masked -->
</div>

<style>
.masked-content {
  /* Reference the SVG mask ID */
  -webkit-mask-image: url(#custom-shape);
  mask-image: url(#custom-shape);
}
</style>

대체 전략

브라우저가 mask-image 또는 접두사가 붙은 버전을 지원하지 않는 경우:

  • 요소가 잘리지 않고 일반 직사각형으로 표시됩니다.
  • 마스크가 없어도 콘텐츠를 읽을 수 있고 레이아웃이 깨지지 않는지 확인합니다 (점진적 개선).
  • 원하는 경우 기능 감지를 사용하여 clip-path로 더 간단한 대체 도형을 제공합니다.
/* Fallback for browsers that do not support masking */
@supports (not (mask-image: url(x))) and (not (-webkit-mask-image: url(x))) {
  .shaped-element {
    /* Use a simple rounded rectangle as fallback */
    clip-path: inset(5% round 15px);
  }
}