Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an svg size to fit its content?

Tags:

svg

I am displaying playing cards using svgs. I do not want the svgs to scale and I don't know how many cards there will be. The cards have a fixed size though. cards as svgs

Is there a way I can easily make the svg container resize to fit the content? Thanks for pointers.

like image 702
Zuabi Avatar asked Jun 12 '18 09:06

Zuabi


People also ask

How do I make SVG fit content?

There is no automatic way to do it. But the simplest approach would be to use the bounding box of the SVG contents, using getBBox() , then update the width and height from that. bbox. x + bbox.

How can I make an SVG scale with its parent container?

We use viewBox to make the SVG image scalable. viewBox = “0 0 100 100”: defines a coordinate system having x=0, y=0, width=100 units and height=100 units. Thus, the SVG containing a rectangle having width=50px and height=50px will fill up the height and width of the SVG image, and all the dimensions get scaled equally.

Does it matter what size an SVG is?

SVG Files Have Infinite Scalability An SVG file has the ability to be resized to any size you'd like without losing image quality. The size of an SVG file doesn't matter, as they will look the same no matter how big or small they appear on your website. And this scalability is important.


1 Answers

There is no automatic way to do it. But the simplest approach would be to use the bounding box of the SVG contents, using getBBox(), then update the width and height from that.

document.getElementById("btn").addEventListener("click", resizeSVG);


function resizeSVG() {
  var  svg = document.getElementById("card-table");
  // Get the bounds of the SVG content
  var  bbox = svg.getBBox();
  // Update the width and height using the size of the contents
  svg.setAttribute("width", bbox.x + bbox.width + bbox.x);
  svg.setAttribute("height", bbox.y + bbox.height + bbox.y);
}
svg {
  background: green;
}

.card {
  fill: white;
  stroke: black;
  stroke-width: 2;
}
<svg id="card-table" width="300" height="150">
  <rect x="10" y="10" width="35" height="50" class="card"/>
  <rect x="55" y="10" width="35" height="50" class="card"/>
  <rect x="100" y="10" width="35" height="50" class="card"/>
</svg>


<br>
<button id="btn">Resize SVG</button>
like image 170
Paul LeBeau Avatar answered Sep 20 '22 17:09

Paul LeBeau