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:

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.

The purpose of this page is to summarize in one place some of the interactive visualizations I have worked on. Most of these were built...

"When you start on your journey to Ithaca, then pray that the road is long, full of adventure, full of knowledge... Always keep Ithaca fixed in your mind. To arrive there is your ultimate goal. But do not hurry the voyage at all." (from "Ithaca", by C. P. Cavafy)