Fixing Android Browser SVG Scaling with max-height
Ever had that moment where you started coding X and instead spent four hours doing Y instead? I just had it, and it stemmed from a quite simple idea: let’s do an embedded SVG bar chart with React (nice library by the way)! Because I just started with Bootstrap which makes it really simple to scale your content to the device at hand, I also wanted the diagram to scale. Easy, right? WRONG!!!
<svg version="1.1" width="100%" viewBox="0 0 200 100"> here are some primitives </svg>
The viewBox attribute defines the internal coordinates for the SVG, and the
width attribute should ensure the SVG fills the container. And it does, at least on desktop. And mobile Chrome. But not Android default browser. I tried different settings of
preserveAspectratio. I tried CSS tricks that should work but they wouldn’t. After some hours, I gave up and went to sleep. And this morning I found this nugget: WebKit long had a bug, where SVG element is resized to 100% height, which on mobile device was interpreted as screen height (not the parent element)!
So long story short, if I use my S5 in portrait mode, the 1080×1920 screen makes the above SVG element 1920 pixels high, with 1080×540 (2:1) diagram in the middle of huge white area. The bug is reported in 2012: https://bugs.webkit.org/show_bug.cgi?id=82489. This was supposedly already fixed, but seems the new version hasn’t trickled to my mobile OS yet. Thankfully, the fix is quite simple and does seem to work, just add max-height to the element:
<svg version="1.1" style="max-height: 100%" viewBox="0 0 200 100"> here are some primitives </svg>
I didn’t even need the width=”100%” because that seems to be the default. Doesn’t hurt, though. So, just sharing this for everyone, maybe Google will index this and help others in need.