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

设置margin左右auto后容器未居中?CSS垂直文本滑动位置异常

解决CSS垂直文本滑动动画的居中偏移问题

问题根源

  1. .container仅设置左右margin auto,但未指定宽度,块级元素默认占满父容器宽度,导致居中失效。
  2. inner使用绝对定位后脱离正常文档流,父元素布局未做对应调整,导致文本块整体偏移。

修改后的完整代码

CSS 部分

@keyframes animate{
  0%,100%{
    top:0;
  }
  20%{
    top:0px;
  }  
  25%{
    top:-50px;
  }
  45%{
    top:-50px;
  }
  50%{
    top:-100px;
  }
  70%{
    top:-100px;
  }
  75%{
    top:-150px;
  }
  95%{
    top:-150px;
  }
}

.container {
  max-width: 800px; /* 限制容器最大宽度,适配不同屏幕 */
  margin-left: auto;
  margin-right: auto;
  text-align: center; /* 让内部文本块居中 */
}

.outer {
  display: inline-block; /* 让宽度适配内容,配合container的text-align实现居中 */
  position: relative;
}

.inner {
  position: absolute;
  height: 50px;
  line-height: 50px;
  font-size: 45px;
  text-transform: uppercase;
  overflow: hidden;
  left: 0; /* 确保与前面的文本对齐 */
  font-weight: 400;
}

.inner span {
  animation: animate 10s ease infinite;
  position: relative;
  color: #e58e26;
  white-space: nowrap; /* 防止单行文本换行,保证动画完整性 */
}

HTML 部分

<div class="container">
  <h1 class="display-4 w3-center w3-animate-right">Hi I'm Raffiel</h1>
  <div class="outer">
    <h1 style="font-size: 45px;">I am, &nbsp;
      <div class="inner">
        <span>
          Graphic Designer<br>
          Digital Marketer<br>
          Video Editor<br>
          Web Designer<br>
        </span>
      </div>
    </h1>
  </div>
</div>

关键修改说明

  • 给.container添加max-width和text-align: center:限制宽度后左右margin auto才会生效,同时让内部文本块居中。
  • 将.outer设为inline-block:使其宽度适配内容,配合容器的居中属性实现整体对齐。
  • 给.inner添加left: 0:确保绝对定位的文本块与前面的"I am,"左对齐,避免偏移。
  • 给.inner span添加white-space: nowrap:防止单行文本被截断换行,保证动画滑动效果正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:45:35