How to solve iPhone Safari Viewport Scaling Bug

How to solve iPhone Safari Viewport Scaling Bug

Those who create responsive design for iPhone may be aware of the viewport scaling bug in iPhone Safari. The bug occurs when you set the viewport width to device-width and rotate the phone to landscape view. This is a known bug for a long time. Today I’m going to share some tips on how to fix this bug.

Problem

View the image below how its seen in an iPhone and rotate the phone from portrait to landscape.

Solution 1: Quick Meta Tag Fix

A quick fix to this issue is by setting maximum-scale=1 in the viewport meta tag. This fixes the problem, but the downside is that the page will no longer be zoomable with the zoom gesture.

<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1">

Solution 2: Javascript

For usability concerns, setting maximum-scale is not an ideal solution because user can not zoom the page. Fortunately, there is a Javascript fix which was discovered by @mathias, @cheeaun and @jdalton. Add the following Javascript in the<head>to fix the viewport scaling bug on orientation change. With this Javascript fix, the page remains zoomable.

<script type="text/javascript"> (function(doc) { var addEvent = 'addEventListener', type = 'gesturestart', qsa = 'querySelectorAll', scales = [1, 1], meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : []; function fix() { meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1]; doc.removeEventListener(type, fix, true); } if ((meta = meta[meta.length - 1]) && addEvent in doc) { fix(); scales = [.25, 1.6]; doc[addEvent](type, fix, true); } }(document)); </script>

1 Comment

  1. Puss 8 years ago

    At last, smeoone comes up with the “right” answer!

Leave a reply

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

*