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

如何将SVG动画圆形在矩形内垂直水平居中且互不重叠

SVG圆点居中实现方案

SVG的<g>分组元素不属于CSS盒模型元素,设置width、margin这类盒模型属性不会生效,SVG内部元素的定位依赖坐标系统,我们可以用以下两种方案实现三个圆点的居中效果:

  • 方案1:用g标签分组+transform平移(不需要修改原有circle的坐标和动画逻辑)
    先计算三个圆点的整体宽度:三个圆点从左边缘到右边缘总宽度为60px(最左圆点左边界x=0,最右圆点右边界x=60),SVG viewBox宽度为500px,所以水平居中需要的x轴偏移量为(500-60)/2=220px,直接给g标签添加transform属性即可,代码如下:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="200" viewBox="0 0 500 100">
      <rect width="100%" height="100%" fill="#f3f3f3"/>
      <!-- 加transform平移实现居中 -->
      <g transform="translate(220, 0)">
        <circle fill="#2FC143" stroke="none" cx="6" cy="50" r="6">
          <animateTransform attributeName="transform" dur="1s" type="translate" values="0 15 ; 0 -15; 0 15" repeatCount="indefinite" begin="0.1"></animateTransform>
        </circle>
        <circle fill="#2FC143" stroke="none" cx="30" cy="50" r="6">
          <animateTransform attributeName="transform" dur="1s" type="translate" values="0 10 ; 0 -10; 0 10" repeatCount="indefinite" begin="0.2"></animateTransform>
        </circle>
        <circle fill="#2FC143" stroke="none" cx="54" cy="50" r="6">
          <animateTransform attributeName="transform" dur="1s" type="translate" values="0 5 ; 0 -5; 0 5" repeatCount="indefinite" begin="0.3"></animateTransform>
        </circle>
      </g>
</svg>
  • 方案2:直接修改每个circle的cx属性
    如果不需要分组,直接给每个circle的cx值统一加上220px的偏移量即可,三个圆点的cx分别改为226、250、274,效果和方案1完全一致。

两种方案都不会影响原有的跳动动画效果,三个圆点的相对间距和动画幅度保持不变,不会出现重叠问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:24:02