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

纯CSS交替文本动画扩展:如何添加第三行文本?

如何给纯CSS交替文本动画添加第三行文本

要给这个纯CSS交替文本动画加第三行,只需要调整HTML结构和CSS关键帧的时间分配,具体修改如下:

修改后的HTML代码

<h1>
  <span class="text_1">Fancy heading on your static web page</span>
  <span class="text_2">What?? How does it change without JavaScript?</span>
  <span class="text_3">Add a third line easily with pure CSS!</span>
</h1>

修改后的CSS代码

body {
  background-color: black;
  color: white;
  font-size: 100px;
}

h1 {
  font-size: 30px;
}

.text_1 {
  animation: text1;
}

.text_2 {
  animation: text2;
}

.text_3 {
  animation: text3;
}

.text_1,
.text_2,
.text_3 {
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
  position: relative;
  animation-duration: 30s; /* 总时长改为30s,适配三个文本循环 */
  animation-timing-function: steps(25, end);
  animation-iteration-count: infinite;
}

.text_1::after,
.text_2::after,
.text_3::after {
  content: "|";
  position: absolute;
  right: 0;
  animation: caret infinite;
  animation-duration: 1s;
  animation-timing-function: steps(1, end);
}

@keyframes text1 {
  0%, 33.33%, 100% { width: 0; }
  10%, 23.33% { width: 17em; } /* 对应第一段文本的宽度 */
}

@keyframes text2 {
  0%, 33.33%, 66.66%, 100% { width: 0; }
  43.33%, 56.66% { width: 21.2em; } /* 对应第二段文本的宽度 */
}

@keyframes text3 {
  0%, 66.66%, 100% { width: 0; }
  76.66%, 89.99% { width: 19em; } /* 对应第三段文本的宽度,需根据实际内容调整 */
}

@keyframes caret {
  0%, 100% { opacity: 0; }
  50% { opacity: 1; }
}

关键修改说明

  • 动画总时长调整:把原来的20s改成30s,让三个文本的交替节奏更均匀,每个文本的展示+过渡周期占10s。
  • 新增第三段文本样式:添加.text_3类并绑定text3动画,同时把它加入到共享样式选择器中。
  • 关键帧时间分配:
    • 第一段文本(text1)在0%-33.33%周期内展示,10%-23.33%保持显示宽度,其余时间宽度为0。
    • 第二段文本(text2)在33.33%-66.66%周期内展示,43.33%-56.66%保持显示宽度。
    • 第三段文本(text3)在66.66%-100%周期内展示,76.66%-89.99%保持显示宽度。
  • 文本宽度适配:每个@keyframes里的width值需要根据你实际的文本内容调整,确保刚好能容纳整个文本,打字效果才会正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:14:54