Web 功能:
遮罩
概览
如需为容器边缘应用透明度渐变(例如,表示有更多内容可滚动或淡出文本),请使用具有线性渐变的 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 */
}
}