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

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: 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

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.

Published by

Joonas Pihlajamaa

Coding since 1990 in Basic, C/C++, Perl, Java, PHP, Ruby and Python, to name a few. Also interested in math, movies, anime, and the occasional slashdot now and then. Oh, and I also have a real life, but lets not talk about it!

4 thoughts on “Fixing Android Browser SVG Scaling with max-height”

  1. Thanks for this tip.

    To offer one in return, we were experiencing the same issue, but with width. We have added both “max-height: 100%” and “max-width: 100%” to the inline styles of all our SVG elements used on Android browsers.

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.