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

CSS打字机效果从中间向两边输入,如何调整为从左到右正常展示?

问题根源

你当前实现的打字机动画从中间向两侧延伸,核心原因是承载动画的.line元素本身为水平居中状态:当宽度从0逐步增加到40em时,元素始终保持页面居中,宽度会向左右两侧同时扩展;搭配你设置的text-align: center和外层justify-content-center属性,内部文字始终位于容器中间,最终就出现了从中间出字的效果。

调整方案

核心思路是让动画元素内部文字左对齐,宽度仅向右侧扩展,再将整个动画组件整体居中,修改后的代码如下:

调整后CSS代码

/* 新增外层居中容器,负责将整个打字机组件在页面居中 */
.typewriter-wrap {
    margin: 260px auto 0;
    position: relative;
    top: 15%;
    width: fit-content;
}
.line {
    border-right: 2px solid rgba(255, 255, 255, 0.75);
    font-size: 100%;
    text-align: left; /* 改为左对齐,保证文字从左侧开始显示 */
    white-space: nowrap;
    overflow: hidden;
}

.anim-typewriter {
    animation: typewriter 4s steps(40) 1s 1 normal both,
    blinkTextCursor 500ms steps(40) infinite normal;
}

@keyframes typewriter {
    from {
        width: 0;
    }
    to {
        width: 100%; /* 改为100%自适应文本长度,不用手动匹配固定宽度 */
    }
}

@keyframes blinkTextCursor {
    from {
        border-right-color: rgba(255, 255, 255, 0.75);
    }
    to {
        border-right-color: transparent;
    }
}

调整后HTML代码

<!-- 外层居中容器,移除原有的justify-content-center属性 -->
<div class="d-flex head typewriter-wrap">
    <div class="line anim-typewriter">
        <h1><b>Maintain the best Example Server.</b></h1>
    </div>
</div>
效果说明

修改后打字机的光标会从最左侧开始,逐字向右显示文字,动画结束后整个标题依然保持在页面居中位置,符合标准打字机效果的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:48:04