Prevent page content zooming on mobile orientation change
Adding viewport tag
No scale when rotate
The first step to make web pages responsive is to add the viewport meta tag to the head section of the page. Then mobile devices will render the page at the correct pixel resolution without zooming out content:
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
For details please read: You will get a different device size and media query breakpoint when viewport meta is applied.
However iPhone/iPad has a bug on this. When you first visit the page, it looks fine. The page fills the width exactly. But when you change orientation the viewport doesn't fit anymore. It zooms in.
If you didn't see this issue, try manually zooming the page, then you will see it for the following orientation changes.
Some posts on the Internet say that it has been fixed in iOS 5. But I can still see this bug with my iPhone 8+ (iOS 12.1.4).
We can avoid this issue by adding "maximum-scale=1.0" to the viewport content, but it is unacceptable to many users as they won't be able to zoom in/out the page anymore.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
We came up with a neat solution for this:
-
Keeps the standard viewport tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
-
Adding a piece of JavaScript code to the page that will add the "maximum-scale=1.0" to the viewport during the device rotation, and then cancel it immediately.
<script> if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) && window.addEventListener && document.querySelector) { window.addEventListener('orientationchange', rotateWithNoScale, false); } function rotateWithNoScale() { var viewport = document.querySelector("meta[name=viewport]"); if (viewport) { var content = viewport.getAttribute("content"); viewport.setAttribute("content", content + ", maximum-scale=1.0"); setTimeout(function () { viewport.setAttribute("content", content); }, 90); } } </script>
You can test it out with your mobile device by switching the two options at the top of the page.