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

如何用CSS动画实现容器内文本从左到右平滑滑动(容器不动)

实现文本在容器内顺滑左右滚动的CSS动画方案

要让文本在白色容器内左右滚动且容器不位移,核心是让容器隐藏溢出内容,同时给文本添加水平位移的CSS动画,具体实现如下:

关键修改点

  • 给.container添加overflow: hidden,确保文本超出容器范围的部分被隐藏,不会撑大容器或导致容器位移
  • 给文本元素(h1)设置white-space: nowrap,避免文本换行,保证滚动是整体水平移动
  • 创建@keyframes定义左右滚动的动画逻辑,通过transform: translateX()实现顺滑位移(比margin性能更优)

修改后的完整代码

body {
  background: red;
}

.container {
  background: white;
  color: black;
  padding: 20px;
  margin: 20px;
  overflow: hidden; /* 隐藏溢出内容 */
}

.container h1 {
  white-space: nowrap; /* 强制文本不换行 */
  animation: slide 3s linear infinite alternate; /* 应用动画:时长3秒,线性速度,无限循环,往返运动 */
}

/* 定义左右滚动的关键帧 */
@keyframes slide {
  from {
    transform: translateX(-80%); /* 从容器左侧外80%位置开始 */
  }
  to {
    transform: translateX(80%); /* 移动到容器右侧外80%位置结束 */
  }
}
<div class="container">
  <h1>Hello world</h1>
</div>

自定义调整说明

  • 动画时长:把3s改成你需要的时间,比如5s会让滚动更慢
  • 位移幅度:调整translateX()的百分比,比如-100%到100%会让文本完全滚出容器再回来,-50%到50%则是在容器内部分滚动
  • 缓动效果:把linear改成ease-in-out可以让滚动在两端有减速效果,更顺滑
  • 循环方式:去掉alternate会让文本滚到右侧后直接跳回左侧,而不是反向滚动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:50:22