CSS多行打字动画失效求助:首行正常,后续内容无法显示
解决CSS多行打字动画文本无法显示的问题
你遇到的核心问题是**white-space:nowrap强制文本单行显示**,配合overflow:hidden直接把超出首行的内容全部隐藏了,这就是第二行及以后文本无法正常显示的原因。要实现多行打字动画,我们需要调整思路,放弃单行强制不换行的规则,试试下面两种方案:
方案一:多元素逐行打字(适合固定行数的文本)
这种方法最简单直接,把每一行文本放在单独的<p>标签里,给每个标签设置打字动画并添加延迟,模拟逐行打字的递进效果。
HTML代码
<div class="col-sm"> <p class="typing-line">i am trying a multiple line css animation of typing.</p> <p class="typing-line">i have some text in p tag . the first line is working perfectly but when some text in not shown.</p> <p class="typing-line">i have used overflow:hidden, white-space:nowrap etc rules to achieve this effect, also added other rules but second line is not working properly.</p> </div>
CSS代码
.typing-line { overflow: hidden; white-space: nowrap; width: 0; margin: 0.5em 0; animation: typing 3s steps(40, end) forwards; } /* 给后续行添加动画延迟,等前一行打完再开始 */ .typing-line:nth-child(2) { animation-delay: 3s; } .typing-line:nth-child(3) { animation-delay: 6s; } @keyframes typing { from { width: 0; } to { width: 100%; } }
这里的steps(40, end)控制打字的“逐字”节奏感,forwards让动画结束后保持文本完全显示的状态,animation-delay实现行与行之间的打字间隔。
方案二:单元素多行打字(适合不固定行数的文本)
如果你的文本行数不固定,可以通过控制元素的max-height来逐步显示多行内容,配合line-height计算需要的显示高度。
HTML代码(保持你原来的结构)
<div class="col-sm"> <p id="intro">i am trying a multiple line css animation of typing. i have some text in p tag . the first line is working perfectly but when some text in not shown. i have used overflow:hidden, white-space:nowrap etc rules to achieve this effect, also added other rules but second line is not working properly.</p> </div>
CSS代码
#intro { overflow: hidden; max-height: 0; line-height: 1.5em; /* 定义每行的高度 */ animation: typing-multi 8s steps(25, end) forwards; } @keyframes typing-multi { from { max-height: 0; } to { max-height: 6em; /* 设置为 目标行数 * line-height,比如4行就是1.5*4=6em */ } }
这种方法通过逐步增加元素的最大高度来显示多行文本,steps的数值可以根据你想要的“逐行”速度调整。如果需要更精细的逐字多行效果,可能需要结合JavaScript把文本拆分为单个字符的<span>,再逐个设置动画。
关键注意点
- 多行打字场景下不要使用
white-space:nowrap,它会强制文本不换行,直接导致后续内容被隐藏。 - 动画的
duration(时长)和steps(步数)需要根据文本长度调整,让打字速度看起来自然流畅。
内容的提问来源于stack exchange,提问作者Md Nahid Hasan




