How to get an svg element to rotate from center using transform-origin?

Viewed 481

I'm attempting a very simple rotation of an svg rect element. I want this element to rotate relative to its center and I'm trying to achieve this using the transform-origin property (see snippet). Despite attempting to rotate from center using "center" or "50%", it never wants to rotate from its true center.

Can anyone explain why this doesn't work? I've seen similar posts about transform-origin being a css property, not an svg property but I believe this is outdated now and transform-origin is supposed to work.

This method works fine on div elements, just not svg elements.

svg {
  border: solid;
}

svg > rect {
  animation: test 3s infinite;
}

@keyframes test {
  100% { 
    transform: rotate(360deg); 
    transform-origin: center center;
  } 
}
<svg width="200" height="110" viewBox="-200 -400 1000 1000">
  <rect width="600" height="300" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>

1 Answers

Don't use the transform-origin in the keyframe and don't forget setting transform-box: fill-box; also.

svg {
  border: solid;
}

svg>rect {
  transform-box: fill-box; /* you need this for SVGs */
  transform-origin: center center; /* moved here */
  animation: test 3s infinite;
}

@keyframes test {
  100% {
    transform: rotate(360deg);
  }
}
<svg width="200" height="110" viewBox="-200 -400 1000 1000">
  <rect width="600" height="300" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>

Related