### SVG and preserveAspectRatio - This Might Save You Some Trouble

For a recent svg visualization I did utilizing the US county svg data from wikipedia, there were a few nagging display issues that were fairly frustrating.  While the problems were somewhat different on desktops and iPad/iPhones, I think that in the end that these were due to the same core issue: not explicitly setting the "preserveAspectRatio" attribute for the relevant svg html element.

There were the two main display problems I was seeing:
• on iPad, the svg map in the middle of the page would methodically move down the page as completely unrelated div's had their content modified
• on my iMac, there would always seem to be too much space above the map and below the title bar; by making the window wider, this space would be reduced, but I could never make sense of why it wasn't obeying all my padding/margin stuff, and I didn't want to resort to absolute positioning
In the end, the problem - at least part of it - was that I was not assigning the "preserveAspectRatio" attribute for the svg html element.  While I have yet to refine it some more, setting the "preserveAspectRatio" attribute to "xMidYMin meet" (yes there is a space in there) tells the browser to make sure the svg element stays at the top of the div, centered horizontally.  Here's a relevant snippet that is working right now fine on my desktop and on my iPad3:

<svg preserveAspectRatio="xMidYMin meet" width="100%" height="100%"  viewBox="0 0 55.22198 351.66797">


I don't know yet if this might cause other problems, but it is certainly a relief to learn that this can seem to help for what I am wanting.

The default value for the "preserveAspectRatio" attribute is "xMidYMid", which puts the thing in the middle both horizontally and vertically.  This explains the desktop behavior I was trying to control in other ways.  I have no idea why the iPad acted the bizarre way it did when "preserveAspectRatio" was not specified.

This O'Reilly Commons page has more (very nice) documentation on preserveAspectRatio.

-bfl