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

CSS transform-origin在Safari缩放时SVG旋转中心偏移问题

Safari缩放后SVG旋转中心偏移的修复方案

当使用transform-origin: center让SVG内的圆形元素绕自身中心旋转时,Chrome、Firefox及100%缩放的Safari均可正常工作,但Safari页面缩放后,旋转中心会偏离元素本身。

问题代码回顾

原CSS及HTML代码如下:

circle {
  stroke: currentColor;
  transform-origin: center;
  animation: 1s infinite rotate-360;
}

@keyframes rotate-360 {
  100% {
    transform: rotate(360deg);
  }
}
<svg viewBox="0 0 50 50">
  <circle fill="none" cx="25" cy="25" r="12" stroke-dasharray="50" stroke-dashoffset="10" />
</svg>

可行修复方案

方案1:添加transform-box: fill-box属性

给circle元素添加transform-box: fill-box,强制浏览器以元素自身的包围盒作为变换参考系,解决Safari缩放后的计算偏差:

circle {
  stroke: currentColor;
  transform-origin: center;
  transform-box: fill-box; /* 关键修复属性 */
  animation: 1s infinite rotate-360;
}

@keyframes rotate-360 {
  100% {
    transform: rotate(360deg);
  }
}

方案2:将动画应用到SVG元素而非内部circle

把旋转动画移到SVG容器上,利用SVG的viewBox定义的稳定坐标系,避免内部元素的变换计算问题:

svg {
  transform-origin: center;
  animation: 1s infinite rotate-360;
}

circle {
  stroke: currentColor;
}

@keyframes rotate-360 {
  100% {
    transform: rotate(360deg);
  }
}

方案3:使用SVG原生动画(最兼容Safari)

放弃CSS动画,改用SVG原生的<animateTransform>元素,完全基于SVG自身坐标系统实现旋转,不受浏览器CSS变换兼容性影响:

<svg viewBox="0 0 50 50">
  <circle fill="none" cx="25" cy="25" r="12" stroke-dasharray="50" stroke-dashoffset="10">
    <animateTransform 
      attributeName="transform" 
      type="rotate" 
      from="0 25 25" 
      to="360 25 25" 
      dur="1s" 
      repeatCount="indefinite" 
    />
  </circle>
</svg>

原因说明

Safari在页面缩放状态下,对SVG内部元素的CSS transform-origin: center计算存在精度问题,导致旋转中心偏移。transform-box: fill-box能强制变换参考系绑定元素自身;将动画移到SVG容器则利用了viewBox的稳定坐标;SVG原生动画则完全绕开CSS变换的兼容性坑,是最可靠的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:52:31