Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Created October 21, 2016 13:39
Show Gist options
  • Star 68 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save john-doherty/2ad94360771902b16f459f590b833d44 to your computer and use it in GitHub Desktop.
Save john-doherty/2ad94360771902b16f459f590b833d44 to your computer and use it in GitHub Desktop.
Trim whitespace from SVG elements
function trimSvgWhitespace() {
// get all SVG objects in the DOM
var svgs = document.getElementsByTagName("svg");
// go through each one and add a viewbox that ensures all children are visible
for (var i=0, l=svgs.length; i<l; i++) {
var svg = svgs[i],
box = svg.getBBox(), // <- get the visual boundary required to view all children
viewBox = [box.x, box.y, box.width, box.height].join(" ");
// set viewable area based on value above
svg.setAttribute("viewBox", viewBox);
}
}
@waldyrious
Copy link

FYI, calling getBBox() only works for inline SVG, not for SVG files embedded using <object> or <embed> (at least in my experience -- I got a NS_ERROR_FAILURE, using Firefox).

@dunstan
Copy link

dunstan commented Dec 15, 2017

Thankkkyoooouuuuuuuuuuu for sharing this.

@ChristinaPolischuk
Copy link

Thank you!

@0xJoroh
Copy link

0xJoroh commented Jun 21, 2020

Thank you a lot.

@ghaisbruno
Copy link

You really helped me by far!! Thank you so much :D

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