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

如何实现CSS文本轮换动画的无限重复效果?

解决CSS文本轮换动画无限重复时的文本堆叠问题

你的问题出在当前动画仅执行一轮,重复触发时首个元素会重新淡入,导致与后续元素堆叠。以下是修复后的实现方案,确保动画无限循环且无堆叠:

修改后的CSS代码

.rotatingText {
  font-family: 'Georgia', serif;
  font-style: italic;
  font-size: 18px;
  text-align: center;
  position: relative; /* 让绝对定位的子元素基于此容器定位 */
  height: 80px; /* 固定高度,避免动画过程中布局跳动 */
}

.rotatingText-adjective {
  font-family: 'Open Sans', sans-serif;
  font-size: 50px;
  font-style: normal;
  font-weight: 700;
  left: 0;
  margin: 0;
  opacity: 0;
  position: absolute;
  right: 0;
  text-align: center;
  text-transform: uppercase;
  top: 50px;
  animation: rotate 9s infinite; /* 总时长9s,对应3个元素各占3s周期,无限循环 */
}

.rotatingText-adjective:nth-of-type(1) {
  animation-delay: 0s;
}

.rotatingText-adjective:nth-of-type(2) {
  animation-delay: 3s; /* 第二个元素延迟3s触发,错开第一个的周期 */
}

.rotatingText-adjective:nth-of-type(3) {
  animation-delay: 6s; /* 第三个元素延迟6s触发 */
}

@keyframes rotate {
  /* 前20%时间保持隐藏状态 */
  0%, 20% {
    opacity: 0;
    transform: translate3d(0, 50px, 0);
  }
  /* 中间50%时间保持可见,稳定显示 */
  25%, 75% {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
  /* 最后20%时间淡出隐藏 */
  80%, 100% {
    opacity: 0;
    transform: translate3d(0, -25px, 0);
  }
}

HTML代码(无需修改)

<h1 class="text-white heading-xl mb-2 position-relative">
  <p class="rotatingText">
    I'll make your website&hellip;

    <span class="rotatingText-adjective">beautiful</span>
    <span class="rotatingText-adjective">maintainable</span>
    <span class="rotatingText-adjective">perfect 👌</span>
  </p>
</h1>

关键修复点说明

  • 给.rotatingText添加相对定位和固定高度,确保子元素定位准确,避免布局偏移。
  • 统一设置所有轮换文本的动画为无限循环,总时长设为3个元素的周期总和(9s)。
  • 通过递增的animation-delay让每个元素按顺序触发动画,不会出现时间重叠。
  • 调整关键帧百分比,让每个元素仅在自己的周期内显示,其余时间保持隐藏,彻底解决重复时的文本堆叠问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:52:51