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

This comment has been minimized.

Copy link

@waldyrious 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

This comment has been minimized.

Copy link

@dunstan dunstan commented Dec 15, 2017

Thankkkyoooouuuuuuuuuuu for sharing this.

@senyqy

This comment has been minimized.

Copy link

@senyqy senyqy commented Mar 18, 2020

Thank you!

@0x1e0000

This comment has been minimized.

Copy link

@0x1e0000 0x1e0000 commented Jun 21, 2020

Thank you a lot.

@ghaisbruno

This comment has been minimized.

Copy link

@ghaisbruno 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
You can’t perform that action at this time.