Phrogz Phrogz - 3 months ago 11x
HTML Question

Calculate size of SVG element in HTML page

How can I reliably ask for the size (in pixels) an SVG element is taking up on the host page?

  • Both
    work in Chrome v34.

  • Neither of those work correctly in Firefox v29. (The former is empty, the latter returns incorrect values.)

Test Page:

The motivation for this question is to get a reliable implementation for this answer, which requires knowing the aspect ratio of the outside of the element. Further, for this question I need to know the actual size of the SVG, or at least something that returns proportionate values across different calls and a resizing element.


I've been down that road before. Unfortunately, most of the functions for getting the size of the <svg> element are buggy in Firefox. The only working solution I found was using window.getComputedStyle(svgElement).width (or height), which needs to be parsed (and also only works when svgElement.display == 'block', which it is in your example). I have adopted your fiddle to work in Firefox:

Update: The issue with display 'inline' was fixed some time ago around Firefox 29.

Update 2: As mentioned in another answer, getBoundingClientRect should also work nowadays.