Search code examples
htmlcsssvg

Rotating svg elements about their center


I have an SVG image, in which there are individual circles that I want to rotate about their own center (the center of the circles). However when I set transform-origin:center, and then apply a transform, it starts rotating about the center of the whole SVG image. Is there any way to set the transform origin such that the circles rotate about their own center?

Here is the original svg image (I cannot paste the original code here so this): SVG image

Here is a jsfiddle for this: https://jsfiddle.net/g9zfcdm3/3/

There are 4 circles in the image. Achieving this with any one cirlce would be good enough. What I actually want to achieve is to animate these circles so that they rotate indefinitely around their own center.


Solution

  • See this (resolved as invalid) bug report in Firefox about your problem: https://bugzilla.mozilla.org/show_bug.cgi?id=1209061

    Normally, CSS transforms on SVG elements are relative to the viewport and not to the element itself. This can be changed by adding transform-box: fill-box:

    svg .rotate {
      animation: rotate 5s linear infinite;
      transform-box: fill-box;
      transform-origin: center;
    }
    
    @keyframes rotate {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    

    Working fiddle: https://jsfiddle.net/g9zfcdm3/10/

    Background

    From the MDN docs about transform-box:

    The transform-box CSS property defines the layout box to which the transform and transform-origin properties relate.

    border-box (default)

    The border box is used as the reference box. The reference box of a is the border box of its table wrapper box, not its table box.

    fill-box

    The object bounding box is used as the reference box.

    Note that it's an experimental feature and probably won't work in IE and Edge.