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

如何使用CSS实现从中心向两端均匀填充的线条加载动画

实现中心向两侧扩展的线条动画方案

下面分两种最常用的纯CSS实现方式,都可以满足2px高、100px宽、中心双向同步填充的需求:

方案1:background渐变实现(最灵活,无额外嵌套)

直接通过控制背景尺寸实现,不需要额外伪元素:

<div class="line"></div>
.line {
  width: 100px;
  height: 2px;
  /* 线条底色,可按需修改 */
  background-color: #eee;
  /* 填充色用线性渐变,默认居中放置 */
  background-image: linear-gradient(#fff, #fff);
  background-repeat: no-repeat;
  background-position: center;
  /* 初始填充宽度为0 */
  background-size: 0 100%;
  /* 动画配置:1秒完成填充,可按需调整时长 */
  animation: lineFill 1s linear forwards;
  /* 若需要hover触发填充,替换上面animation代码为下面的transition规则即可
  transition: background-size 1s linear;
  */
}
/* hover触发时增加该规则
.line:hover {
  background-size: 100% 100%;
}
*/

@keyframes lineFill {
  to {
    /* 填充宽度变为100% */
    background-size: 100% 100%;
  }
}

方案2:transform缩放实现(性能最优)

利用transform的GPU加速特性,适合大量动画同时触发的场景:

<div class="line-container">
  <div class="line-fill"></div>
</div>
.line-container {
  width: 100px;
  height: 2px;
  background-color: #eee;
}
.line-fill {
  height: 100%;
  background-color: #fff;
  /* 变换原点设为中心点 */
  transform-origin: center;
  /* 初始横向缩放为0 */
  transform: scaleX(0);
  animation: lineScale 1s linear forwards;
}

@keyframes lineScale {
  to {
    transform: scaleX(1);
  }
}

原理解释

之前只能实现单向填充,大概率是直接修改元素width且没有控制对齐原点,或者变换原点设置在了左/右侧。以上两种方案都是将填充的原点固定在中心,扩展过程中自然向左右两侧等比例延伸,完全符合你给出的效果示意。

内容的提问来源于stack exchange,提问作者m-naeem66622

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:27:03