視覺紋理內容

網頁功能: 遮罩

總覽

如要為元素套用逼真的風化或紋理圖案 (例如髒汙、雜訊或紙張紋理),請使用 CSS 遮罩 (mask-image) 搭配重複的紋理圖片。這樣一來,您就能將內容部分設為半透明,讓內容本身呈現紋理,而不只是在上方疊加紋理。這會產生更逼真的實體材質外觀。

導入作業

如要套用紋理圖案,請按照下列步驟操作:

這是最常見的擬真紋理方法。

.weathered-element {
  /* MANDATORY: Use vendor prefix for wider support in older browsers */
  -webkit-mask-image: url('grunge-pattern.png');
  -webkit-mask-repeat: repeat; /* Repeat the pattern to fill the area */
  -webkit-mask-size: 300px; /* Control the scale of the texture */

  /* Standard property for modern browsers */
  mask-image: url('grunge-pattern.png');
  mask-repeat: repeat;
  mask-size: 300px;
}

方法 2:使用 CSS 漸層建立幾何圖案

您可以使用 CSS 漸層產生圖案。這是獨立檔案,不需要外部圖片檔。

.patterned-element {
  --checkerboard-gradient: 
    linear-gradient(45deg, #000 25%, transparent 25%), 
    linear-gradient(-45deg, #000 25%, transparent 25%), 
    linear-gradient(45deg, transparent 75%, #000 75%), 
    linear-gradient(-45deg, transparent 75%, #000 75%);

  /* Apply a checkerboard pattern as a mask */
  -webkit-mask-image: var(--checkerboard-gradient);
  -webkit-mask-size: 20px 20px;
  -webkit-mask-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  
  mask-image: var(--checkerboard-gradient);
  mask-size: 20px 20px;
  mask-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

Alpha 與亮度遮罩模式

根據預設,CSS 遮罩會使用 mask-mode: match-source。這表示瀏覽器會根據您提供的來源類型,自動決定要使用遮罩的 Alpha 色版 (透明度) 還是亮度:

遮罩來源類型 預設遮蓋模式 遮罩行為
內嵌 SVG <mask> 元素 luminance 不透明度取決於顏色亮度。白色會顯示內容,黑色會隱藏內容,灰色則會建立半透明效果。
直接圖片檔 (例如 PNG、SVG 檔案) alpha 不透明度取決於透明度。不透明部分會顯示內容,透明部分則會隱藏內容。
CSS 漸層 alpha 不透明度取決於透明度。不透明顏色 (例如 black) 會顯示內容,透明顏色則會隱藏內容。

備用策略

如果瀏覽器不支援 mask-image 或前置版本:

  • 元素會顯示為純色,不含紋理。
  • 確保內容在沒有紋理的情況下仍可閱讀 (漸進增強)。
  • 您可以使用背景圖片或疊加層做為備用,模擬材質,但這不會影響內容本身的透明度。
/* Fallback: Use a background image for browsers without mask support */
@supports (not (mask-image: url(x))) and (not (-webkit-mask-image: url(x))) {
  .weathered-element {
    /* Fallback adds texture on top or behind, depending on implementation */
    background-image: url('grunge-pattern.svg');
    background-color: #fff; /* Ensure background is solid if needed */
  }
}