CSS Transform Origin Issue on SVG Sub-Element
When working with SVGs, it can be challenging to control the transform origin of sub-elements. By default, CSS animations and transformations use the overall SVG's (0,0) origin, not the center of the specific element being animated.
Understanding the Issue
In the example provided, the intention is to scale the sub-element "animated-box" from its center. However, the animation begins from the SVG's (0,0) origin, giving the illusion that the box is "flying in from the top left."
Solution: Transform Box
To set the transform origin relative to the animated element, we can use the "transform-box" property:
<code class="css">transform-box: fill-box;</code>
The "fill-box" value tells the browser to use the sub-element's bounding box (the area it fills) as the transform origin. This ensures that the animation scales from the center of "animated-box" as intended.
Updated Example
Applying the transform-box property to our example:
<code class="css">@keyframes scaleBox { from {transform: scale(0);} to {transform: scale(1);} } #animated-box { transform-box: fill-box; animation: scaleBox 2s infinite; }</code>
<code class="html"><svg ...> ... <rect id="animated-box" ...> ... </svg></code>
Now, the "animated-box" scales from its center, creating a smoother and more accurate animation.
The above is the detailed content of Why Does My SVG Sub-Element Animation Start From the Wrong Origin?. For more information, please follow other related articles on the PHP Chinese website!