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

如何让动画中的水平线向右侧收缩而非向中心收缩?

实现线条向右侧收缩的动画调整方案

当前代码中线条向中心收缩的原因是元素通过left: 50%和transform: translate(-50%, -50%)保持居中,宽度变化时左右边缘会同时向中心靠拢。要实现向右侧收缩(右边缘固定,左边缘向右收窄至消失),只需修改收缩动画的定位规则:

  • 在contractLine关键帧中,将元素的定位基准从左侧居中改为右侧对齐,同时将宽度收窄至0。

修改后的完整代码如下:

body {
  margin: 0;
  background: black;
}

.white-line {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 10px;
  background-color: red;
  transform: translate(-50%, -50%);
  animation: expandLine 0.3s ease-in-out forwards 1.2s, moveUp 1.5s ease-in-out forwards 1.41s, contractLine 0.5s ease-in-out forwards 3.3s;
  z-index: 1000;
}    

@keyframes expandLine {
  100% {width: 100%; opacity: 1;}
}

@keyframes moveUp {
  100% {top: 0%;}
}

@keyframes contractLine {
  100% {
    width: 0;
    left: auto;
    right: 0;
    transform: translateY(0);
  }
}
<div class="white-line"></div>

原理说明

  1. 收缩动画触发时,将left设为auto、right设为0,让元素的右边缘固定在屏幕右侧;
  2. 用transform: translateY(0)覆盖原有的垂直偏移(moveUp动画已将top设为0%,无需再垂直居中);
  3. 宽度从100%收窄至0时,元素左边缘向右移动,最终在右侧收缩至消失,完全符合向右侧收缩的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 16:25:58