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

Bootstrap 5.0.2中设置width:100%后居中CSS动画仍不对称

问题:Bootstrap按钮中心对称扩展动画右侧超出

使用Bootstrap 5.0.2,期望实现按钮从中心向左右对称扩展至可用宽度100%的动画,但实际效果不符合预期:动画元素右侧超出对称线(宽度过宽)。

用户代码如下:

<!--bootstrap-->

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<!--code-->

<div class="container bg-success">
  <div class="border border-dark">

    <div class="row m-2 w-animate">
      <a target="_blank" href="velo-art" class="btn bg-animate border border-dark rounded-pill fs-1 col-12  text-center p-2">
        test
      </a>
    </div>
    <div class="row m-2 w-animate">
      <a target="_blank" href="velo-art" class="btn bg-animate border border-dark rounded-pill fs-1 col-12  text-center p-2">
        test_2
      </a>
    </div>
    <div class="row m-2 w-animate">
      <a target="_blank" href="velo-art" class="btn bg-animate border border-dark rounded-pill fs-1 col-12  text-center p-2">
        test_3
      </a>
    </div>
    
  </div>
</div>

<style>
.w-animate {
  position: relative;
  width: 50%;
  left: 25%;
  animation: center-animate 3s ease infinite alternate;
}
.w-animate:hover {
  animation-play-state: paused;
}

@keyframes center-animate {
  0% {
    width: 50%;
    left: 25%;
  }
  100% {
    width: 100%;
    left: 0%;
  }
}
</style>

问题原因

核心问题是Bootstrap的.row类自带左右负margin(默认值为margin-right: -12px; margin-left: -12px):

  • 初始状态下,.row的实际宽度是父容器的50% + 24px(左右负margin的总和),视觉上已经偏右
  • 动画到100%宽度时,left:0%加上负margin,元素右侧直接超出父容器边界,破坏对称效果

修复方案

方式1:清除.row的负margin

给所有带.w-animate的.row添加mx-0类(Bootstrap内置类,清除左右margin):

<div class="row m-2 w-animate mx-0">
  <a target="_blank" href="velo-art" class="btn bg-animate border border-dark rounded-pill fs-1 col-12  text-center p-2">
    test
  </a>
</div>

此时原CSS动画无需修改,width:50% + left:25%就能保持严格居中,动画扩展时会对称填满父容器。

方式2:用transform实现居中(更稳定)

放弃left和width的组合,改用transform: translateX()实现居中,彻底规避margin干扰:

.w-animate {
  position: relative;
  width: 50%;
  left: 50%;
  transform: translateX(-50%);
  animation: center-animate 3s ease infinite alternate;
}
.w-animate:hover {
  animation-play-state: paused;
}

@keyframes center-animate {
  0% {
    width: 50%;
    left: 50%;
    transform: translateX(-50%);
  }
  100% {
    width: 100%;
    left: 50%;
    transform: translateX(-50%);
  }
}

这种方式下,无论元素是否有额外margin/padding,都能保持完美居中,动画扩展时严格从中心向左右对称展开。

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

相关产品推荐
方舟 Agent Plan

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

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