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

打字机动画移动端文本无法居中的问题求助

移动端打字机动画文本居中修复方案

问题现象

打字机动画在桌面端显示时文本居中正常,但移动端初始状态居中,动画过程中文本会向右超出页面范围,需确保移动端文本始终居中。

核心原因

动画过程中元素使用固定宽度从0拉伸到目标值,移动端由于视口宽度小、字体大小适配问题,固定宽度的容器在动画时无法保持相对视口的居中定位,导致内容偏移溢出。

修复方案

修改思路

  • 让容器自适应内容宽度,避免固定宽度带来的适配冲突
  • 调整打字机动画逻辑,确保文本从左侧开始逐字显示,同时容器始终保持居中
  • 优化移动端的内边距与字体大小,避免视口溢出

修改后的完整代码

CSS 部分

@import url(https://fonts.googleapis.com/css?family=Anonymous+Pro);

html{
  min-height: 100%;
  overflow: hidden;
}
body{
  height: calc(100vh - 8em);
  padding: 3.5em;
  color: #fff;
  font-family: 'Anonymous Pro', monospace;  
  background-color: rgb(25,25,25); 
  /* 移动端适配:减少内边距 */
  @media (max-width: 768px) {
    padding: 1.5em;
  }
}
.line-1{
    position: relative;
    top: 10%;  
    /* 移除固定宽度,改用inline-block自适应内容 */
    display: inline-block;
    margin: 0 auto;
    border-right: 2px solid rgba(255,255,255,.75);
    font-size: 220%;
    text-align: left; /* 文本左对齐,确保动画从左侧开始 */
    white-space: nowrap;
    overflow: hidden;
    transform: translateY(-50%);
    /* 移动端适配:缩小字体 */
    @media (max-width: 768px) {
      font-size: 150%;
    }
}

.anim-typewriter{
  animation: typewriter 2.2s steps(20) 0.9s 1 normal both,
             blinkTextCursor 500ms steps(20) 0s 13 normal both;
}
@keyframes typewriter{
  from{width: 0;}
  /* 目标宽度改为自适应内容的实际宽度 */
  to{width: fit-content;}
}
@keyframes blinkTextCursor{
  from{border-right-color: rgba(255,255,255,.75);}
  to{border-right-color: transparent;}
}

HTML 部分

<html>
<body>
<!-- 新增父容器确保inline-block元素居中 -->
<div style="text-align: center; width: 100%;">
  <p class="line-1 anim-typewriter">12345.6789123<span style="color: #27B59D;">/12345</span></p>
</div>
</body>
</html>

关键修改点说明

  • 将.line-1的display改为inline-block,移除固定宽度,让容器根据文本内容自动调整宽度,配合父容器的text-align: center始终保持居中
  • 打字机动画的目标宽度改为fit-content,避免固定数值在移动端的适配问题
  • 添加媒体查询,针对移动端减少body内边距、缩小字体大小,防止内容溢出视口
  • 文本对齐改为left,确保打字机动画从文本左侧开始逐字显示,视觉更自然

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:40:23