網頁功能:
遮罩
總覽
如要對容器邊緣套用透明度漸層 (例如表示有更多內容可捲動,或淡出文字),請使用 CSS 遮罩搭配線性漸層。這種做法比使用半透明疊加層更好,因為它會實際淡化內容本身,讓背景自然顯示,不會干擾文字選取或指標事件。
導入作業
如要實作柔邊淡出效果,請按照下列步驟操作:
淡出容器底部邊緣
這項功能可用來表示可捲動區域下方還有更多內容。
.container {
/* Enable scrolling */
overflow-y: auto;
/* MANDATORY: Use vendor prefix for wider support in older browsers */
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
/* Standard property for modern browsers */
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
}
頂端和底部邊緣都淡出
您可以使用單一漸層搭配多個顏色停止點,讓兩側邊緣都淡出。
.dual-fade-container {
/* Content is visible between 10% and 90% of the height */
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 10%, black 90%, transparent 100%);
mask-image: linear-gradient(to bottom, transparent 0%, black 10%, black 90%, transparent 100%);
}
備用策略
如果瀏覽器不支援 mask-image 或前置版本:
- 內容不會淡出,且會顯示清晰的邊緣。
- 確保介面仍可正常運作,且內容在沒有淡出效果的情況下仍可閱讀 (漸進增強)。
- 您可以使用半透明疊加層做為備用方案,但請注意,這需要知道背景顏色,且可能會干擾文字選取,除非使用
pointer-events: none。
/* Fallback using an overlay for browsers that do not support masking */
@supports (not (mask-image: linear-gradient(to bottom, black, transparent))) and (not (-webkit-mask-image: linear-gradient(to bottom, black, transparent))) {
.container {
position: relative;
}
.container::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 20%;
/* Fallback assumes a solid background color (e.g., white) */
background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,1));
pointer-events: none; /* Allow interaction with text underneath */
}
}