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.
Is there a way I can easily make the svg container resize to fit the content? Thanks for pointers.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With