Whilst working with some SVG (Scalable Vector Graphics) images in my latest project, I experienced some strange behavior that took a bit of debugging to figure out. I needed to setup the image so that it would dynamically adjust its size if the browser window was resized, and also retain its aspect ratio whilst doing this.

After exploring my options I found that a few things needed to be done in order for this to work:

  1. Set the “viewBox” dimension attribute on the SVG element in the DOM.
  2. Remove the “width” and “height” attributes from the root SVG element, in the SVG data file itself.
  3. Add in the “preserveAspectRatio” attribute to the SVG element in the DOM, with a value of “xMinYMin meet”

Some more detail on these properties can be seen on Stackoverflow here.

The first example I created worked correctly, however when I implemented this in my project the scaling was still broken. The “preserveAspectRatio” attribute was definitely being set on the SVG element, but it was only taking effect after I manually removed and re-added it via Developer Tools….

It turns out that the problem was due to setting the attribute using jQuery, as the .attr() function will convert properties to lowercase before assigning them. One solution is simply to use standard DOM functions for this: e.g.
document.getElementsByTagName("svg")[0].setAttribute("preserveAspectRatio", "xMinYMin meet").

Alternatively you can add in a small fix that I found on StackOverflow here. This fix simply overrides the default hook for jQuery.attr() so that it uses the correctly capitalised version of the property name:

Leave a Reply

Your email address will not be published. Required fields are marked *