Autosize an SVG?

An alternative is to do similar to the above JS but set viewBox (note, not viewbox!) instead of width and height from JS with values from the getBBox() call. Then use preserveAspectRatio="xMidYMid meet" or similar.

var svg = document.getElementById("x1");
svg.setAttribute("viewBox", "0 0 32 18.4");

https://jsfiddle.net/t88pLgbb/4/


If the SVG element does not have any width and height attributes, then the width/height should be calculated according to the CSS specs, as pointed out by Robert Longson. However, those values will not reflect the proper dimensions of the SVG's content. You can find out the proper dimensions and placement using getBBox():

// Javascript to run after document load
var svg = document.getElementsByTagName("svg")[0];
var bbox = svg.getBBox();
svg.setAttribute("width", bbox.width + "px");
svg.setAttribute("height", bbox.height + "px");
svg.setAttribute("viewBox", `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`);
<svg xmlns="http://www.w3.org/2000/svg" style="background-color: red">
  <rect x="30" y="40" width="50" height="60"/>
</svg>

Tags:

Css

Svg