April 17, 2024
The Trick to Animating SVG Viewbox
Justin Golden
webdev
svg
css

The Expectation
You may think you could animate SVG viewbox in CSS per usual:
svg {
transition: viewBox 1s linear;
} and then set the values with JS:
mySvg.setAttribute('viewBox', '0 0 100 100'); But this doesn’t work. The JS sets the viewBox, but it doesn’t animate.
(by the way, remember “viewBox” has a capital “B”)
Animate Element
You can use the <animate> element in SVG:
<animate attributeName="viewBox" to="0 0 100 100" dur="1s" fill="freeze" /> But this runs on page load and doesn’t have dynamic data.
For example, if you wanted a dynamic width and height:
mySvg.setAttribute('viewBox', `0 0 ${width} ${height}`); then you wouldn’t be able to.
The Solution
The solution is to add the animate element without a to attribute:
<animate attributeName="viewBox" dur="1s" fill="freeze" /> Then set the to in JS, and then call the beginElement() method on the animate:
mySvg.querySelector('animate').setAttribute('to', `0 0 ${width} ${height}`);
mySvg.querySelector('animate').beginElement(); More Blog Articles
