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

使用background-clip:text实现文字滚动变色动画的问题

文字颜色切换滚动动画实现问题

想要实现文字在屏幕中间位置切换颜色的动画效果,效果如下:
文字颜色切换效果

当前使用的HTML代码:

<div class="text-mask">
    <div class="scrolling-text">MASKED TEXT</div>
</div>

CSS代码:

body {
  background-color: #000;
}
.text-mask {
  font-size: 100px;
  font-weight: bold;
  background: linear-gradient(to right, orange 50%, white 50%);
  background-clip: text;
  color: transparent;
  position: relative;
  height: 120px;
}

.scrolling-text {
  /* transform: translateX(10px); */
  /* position: relative */
} 

遇到的问题:只要给.scrolling-text添加样式(如transform: translateX(10px)),文字就会消失。希望通过修改transform值实现文字滚动动画,请问如何解决?


问题原因

文字消失是因为background-clip: text作用在父元素.text-mask上,而子元素.scrolling-text添加transform后会创建新的堆叠上下文,导致父元素的文字裁剪效果无法作用到子元素的文字上,最终文字因color: transparent且没有有效背景填充而消失。

解决方案

把背景渐变和文字裁剪的样式直接应用到.scrolling-text元素上,同时调整布局让文字居中,再添加滚动动画即可:

body {
  background-color: #000;
  /* 让容器居中 */
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}
.text-mask {
  font-size: 100px;
  font-weight: bold;
  position: relative;
  /* 可选:限制容器宽度,防止滚动时文字溢出 */
  overflow: hidden;
}

.scrolling-text {
  background: linear-gradient(to right, orange 50%, white 50%);
  background-clip: text;
  color: transparent;
  /* 添加滚动动画 */
  animation: scrollAnimation 4s linear infinite;
}

@keyframes scrollAnimation {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

如果想要实现文字固定、颜色渐变滚动的效果(即文字不动,颜色分界左右移动),可以修改动画作用于背景位置:

.scrolling-text {
  background: linear-gradient(to right, orange 50%, white 50%);
  background-clip: text;
  color: transparent;
  background-size: 200% 100%;
  animation: colorShift 3s ease-in-out infinite alternate;
}

@keyframes colorShift {
  0% {
    background-position: 0% 0%;
  }
  100% {
    background-position: 100% 0%;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:53:25