You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

YouTube复刻项目:推荐视频上方栏位文本渐变实现求助

YouTube标签栏文本渐隐实现方案

标签栏效果示例

我正在复刻YouTube的标签栏,已经用linear-gradient实现了按钮背景的渐隐效果,但不知道怎么给文本做同样的渐隐。尝试直接给文本加linear-gradient没效果,我的HTML和CSS代码如下:

现有代码

CSS

#bar-wrap{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    gap: 0.6rem;
    font-size: 0.9rem;
    align-items: center;
    overflow-x: scroll;
    white-space: nowrap;
}
#bar-wrap .button{
    background-color: rgb(211,211,211);
    color: black;
    width: fit-content;
    height: 2rem;
    border-radius: 0.8rem;
    padding: 0.4rem;
    cursor: pointer;


    display: flex;
    align-items: center;
    justify-content: center;
}

HTML

<div id="bar-wrap">
  <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>

解决方案

一、容器边缘整体文本渐隐(YouTube同款效果)

当标签栏横向滚动到右侧时,让边缘标签文本逐渐隐入背景,只需给容器添加伪元素遮罩:

修改#bar-wrap的CSS:

#bar-wrap{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    gap: 0.6rem;
    font-size: 0.9rem;
    align-items: center;
    overflow-x: scroll;
    white-space: nowrap;
    position: relative; /* 开启相对定位 */
    /* 可选:隐藏滚动条,和YouTube一致 */
    scrollbar-width: none;
}
/* 适配webkit内核浏览器隐藏滚动条 */
#bar-wrap::-webkit-scrollbar{
    display: none;
}
/* 添加右侧渐隐遮罩 */
#bar-wrap::after{
    content: '';
    position: absolute;
    right: 0;
    top: 0;
    width: 60px; /* 遮罩宽度,可按需调整 */
    height: 100%;
    /* 渐变从透明过渡到页面背景色,这里#fff替换成你的实际背景色 */
    background: linear-gradient(to right, transparent, #ffffff);
    pointer-events: none; /* 不干扰下方元素的点击和滚动 */
}

二、单个按钮内文本过长时的渐隐

如果想让单个按钮里的长文本自身渐隐,需要用background-clip: text配合渐变:

修改.button的CSS:

#bar-wrap .button{
    background-color: rgb(211,211,211);
    color: transparent; /* 文本设为透明,让背景渐变透出来 */
    width: fit-content;
    max-width: 120px; /* 限制按钮最大宽度,按需调整 */
    height: 2rem;
    border-radius: 0.8rem;
    padding: 0.4rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    /* 文本渐变效果,从黑色过渡到透明 */
    background-image: linear-gradient(to right, #000, transparent);
    background-clip: text; /* 将背景裁剪到文本区域 */
    overflow: hidden; /* 隐藏超出按钮宽度的文本 */
}

内容的提问来源于stack exchange,提问作者Krzyziiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:00:22