Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

waldyrious commented Sep 18, 2017

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.

@senyqy
Copy link

senyqy commented Mar 18, 2020

Thank you!

@0xJoroh
Copy link

0xJoroh commented Jun 21, 2020

Thank you a lot.

@ghaisbruno
Copy link

ghaisbruno commented Aug 12, 2020

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