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. To see this in action, view the bug demo page with your iPhone and rotate the phone from portrait to landscape view (you should see the page being scaled up). 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 demo)

View the demo page with an iPhone and rotate the phone from portrait to landscape.

viewport bug

Solution 1: Quick Meta Tag Fix (view demo)

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 (view demo)

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>

Comments?

Do you know more solutions to fix this viewport scaling bug? The Javascript fix is particularly useful for coding responsive web design. Please share in the comments.