Skip to content

Instantly share code, notes, and snippets.

@adamcbrewer
Last active February 5, 2021 09:06
Show Gist options
  • Save adamcbrewer/f3086d494ecc6c1de1da to your computer and use it in GitHub Desktop.
Save adamcbrewer/f3086d494ecc6c1de1da to your computer and use it in GitHub Desktop.
JS: Trim SVG viewbox
/**
* Will trim the whitespace around the SVG's viewbox
*
*/
var svg = document.getElementsByTagName("svg")[0];
var bbox = svg.getBBox();
var viewBox = [bbox.x, bbox.y, bbox.width, bbox.height].join(" ");
svg.setAttribute("viewBox", viewBox);
@zogreptile
Copy link

zogreptile commented Sep 11, 2020

If i get the idea properly, it's also necessary to set the width and height svg attributes with the calculated bbox.width, bbox.height values.

@adamcbrewer
Copy link
Author

@zogreptile you don't have to set the width or height unless you need a default size for them. I personally use CSS for that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment