
本文详解如何为水平滚动导航栏中的文字添加右侧线性渐隐效果,通过伪元素叠加透明度渐变层实现视觉过渡,避免生硬截断,提升 ui 专业感。
本文详解如何为水平滚动导航栏中的文字添加右侧线性渐隐效果,通过伪元素叠加透明度渐变层实现视觉过渡,避免生硬截断,提升 ui 专业感。
在构建 YouTube 类似推荐页顶部标签栏时,仅对按钮背景应用 linear-gradient 并不能让文字本身产生“向右淡出”的视觉效果——因为 CSS 的 background: linear-gradient() 作用于容器背景,而非文本内容。直接对
设置 background-clip: text 和 -webkit-text-fill-color: transparent 虽可实现文字渐变色,但无法实现“右侧透明化”这种遮罩式渐隐(fade-out)效果,尤其当内容超出可视区域时。
正确方案是:使用绝对定位的伪元素(::after)作为渐隐遮罩层,覆盖在文字容器上方,通过从透明到不透明的水平渐变,模拟自然的视觉收束。
Youtube Script
下载
YouTube视频脚本、标题A/B测试、缩略图文案、SEO优化、开头Hook、章节标记。YouTube script writer with title testing, thumbnail copy, SEO optimization, hooks.
以下是完整、可直接复用的实现方案:
✅ HTML 结构(语义清晰,嵌套合理)
<div id="bar-wrapper">
<div id="bar-scroll">
<div class="button" onclick="barActive(this)">Wszystkie</div>
<div class="button" onclick="barActive(this)">Źródło: Ixo Music</div>
<div class="button" onclick="barActive(this)">Podobne</div>
<div class="button" onclick="barActive(this)">Na żywo</div>
<div class="button" onclick="barActive(this)">Ostatnio przesłane</div>
<div class="button" onclick="barActive(this)">Obejrzane</div>
</div>
</div>
✅ CSS 样式(含渐隐 + 无痕滚动)
/* 外层容器:提供相对定位上下文 */
#bar-wrapper {
position: relative;
width: 100%;
height: 2.6rem; /* 确保容纳按钮高度与内边距 */
}
/* 渐隐遮罩层 —— 关键! */
#bar-wrapper::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
/* 从左75%处开始透明 → 右侧100%完全不透明,形成向右淡入(即左侧可见,右侧渐隐) */
background: linear-gradient(
90deg,
transparent 75%,
rgba(255, 255, 255, 0.95) 95%,
white 100%
);
/* 若需更柔和过渡,可延长渐变区间(如 80% → 98%) */
}
/* 滚动容器:flex 布局 + 隐藏原生滚动条 */
#bar-scroll {
display: flex;
align-items: center;
gap: 0.6rem;
font-size: 0.9rem;
overflow-x: auto;
white-space: nowrap;
padding-right: 1.2rem; /* 预留遮罩空间,避免最右按钮被完全盖住 */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE/Edge */
}
#bar-scroll::-webkit-scrollbar {
display: none; /* Chrome/Safari */
}
/* 按钮基础样式 */
.button {
background-color: #d3d3d3;
color: #000;
border-radius: 0.8rem;
padding: 0.4rem 0.8rem;
cursor: pointer;
min-width: 5rem;
text-align: center;
transition: background-color 0.2s;
}
.button:hover {
background-color: #c0c0c0;
}
.button.active {
background-color: #0f80ff;
color: white;
}
⚠️ 注意事项与优化建议
- 遮罩位置精准性:#bar-wrapper::after 必须覆盖整个滚动区域,因此其父容器 #bar-wrapper 需设 position: relative,确保绝对定位生效。
- 渐变方向逻辑:linear-gradient(90deg, ...) 是从左到右;若希望左侧淡出(如向右滚动时左端隐藏),则将渐变改为 transparent 0%, rgba(...) 20%, white 35% 并调整 left 起点。
- 响应式适配:在小屏设备上,建议配合 @media (max-width: 768px) 缩小 font-size 和 padding,并确保 gap 不导致换行。
- 无障碍提示:渐隐仅为视觉增强,不影响可访问性;确保按钮仍具备足够对比度(WCAG AA),且焦点状态清晰可见。
该方案兼容所有现代浏览器(Chrome 10+, Firefox 90+, Safari 15.4+),无需 JS 计算,性能高效,是实现 YouTube 风格导航栏“优雅截断”的工业级实践。










