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

CSS打字动画失效求助:H1文本无法实现逐字输出效果

CSS打字动画未生效问题排查

问题描述

尝试为H1文本添加逐字输出的打字动画,但动画未生效。

原代码

HTML

<div class="techBox">
   <div class="techTitle"><h1>Website Design</h1></div>
</div>

CSS

.techBox {
    background: rgb(0, 0, 0);
    border: 2px solid rgb(0, 150, 5);
    box-shadow: 0px 0px 40px rgb(0, 150, 5);
    width: 80%;
    height: 80%;
    position: relative;
    bottom: 750px;
    left: 150px;
    border-radius: 40px;
    text-align: center;
}

.techTitle h1{
    overflow: hidden;
    width: 450px;
    letter-spacing: .10em;
    border-right: .15em solid rgb(0, 150, 5);
    color: rgb(0, 150, 5);
    font-size: 45px;
    font-family: 'Roboto Mono', sans-serif;
    animation: typing 3.5s steps(40, end);
    animation: caret .75s step-end infinite;
    margin: 0 auto;
    white-space: nowrap;
}

@keyframes typing {
    from {width: 0}
    to {width: 100%;}
}

@keyframes caret {
    from, to{border-color: transparent}
    50% {border-color: rgb(0, 150, 5)}
}

问题原因

  1. 重复属性覆盖:在.techTitle h1里连续写了两个animation属性,CSS中同一属性重复声明时,后面的会覆盖前面的,导致typing动画被caret动画完全覆盖,根本没执行。
  2. 初始宽度固定:设置了固定的width: 450px,而typing动画是从width: 0过渡到width: 100%,固定宽度直接抵消了动画的变化效果。
  3. steps参数不匹配:steps(40, end)中的40远大于文本实际字符数("Website Design"含空格共14个字符),会让动画节奏完全偏离预期。

修复后的代码

修改.techTitle h1的CSS规则,核心调整动画声明、初始宽度和steps参数:

.techTitle h1{
    overflow: hidden;
    width: 0; /* 初始宽度设为0,让动画从无到有 */
    letter-spacing: .10em;
    border-right: .15em solid rgb(0, 150, 5);
    color: rgb(0, 150, 5);
    font-size: 45px;
    font-family: 'Roboto Mono', sans-serif;
    /* 合并两个动画,逗号分隔,同时添加forwards保持结束状态 */
    animation: typing 3.5s steps(14, end) forwards, caret .75s step-end infinite;
    margin: 0 auto;
    white-space: nowrap;
}

@keyframes typing {
    from {width: 0}
    to {width: 100%;}
}

@keyframes caret {
    from, to{border-color: transparent}
    50% {border-color: rgb(0, 150, 5)}
}

关键修改说明

  • 合并两个动画到同一个animation属性,用逗号分隔,确保两个动画都能正常执行。
  • 给typing动画添加forwards关键字,让动画结束后保持最后一帧状态(宽度100%),避免文字变回隐藏。
  • 初始宽度设为0,确保动画从完全隐藏的状态开始过渡。
  • 将steps(40, end)改为steps(14, end),匹配文本实际字符数,让逐字输出的节奏更精准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:36:10