Mobile Development

Prevent iOS From Zooming Form When Fields Are In Focus

Written by Kevin Liew on 22 Mar 2017
2,865 Views • Shares
0 comments

Okay, this is something that I found out not too long ago and it's mind blowing. Maybe I discovered this a bit too late but I decided to write a post about it just to make sure you know about this as well.

All the while, I have been using Javascript solution from HTML5 Mobile Boilerplate which works pretty great. Here's the code snippet which prevent form field zooming by changing viewport content.

/**
 * Prevent iOS from zooming onfocus
 * https://github.com/h5bp/mobile-boilerplate/pull/108
 * Adapted from original jQuery code here: http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
 */

MBP.preventZoom = function() {
  if (MBP.viewportmeta && navigator.platform.match(/iPad|iPhone|iPod/i)) {
    var formFields = document.querySelectorAll('input, select, textarea');
    var contentString = 'width=device-width,initial-scale=1,maximum-scale=';
    var i = 0;
    var fieldLength = formFields.length;

    var setViewportOnFocus = function() {
        MBP.viewportmeta.content = contentString + '1';
    };

    var setViewportOnBlur = function() {
        MBP.viewportmeta.content = contentString + '10';
    };

    for (; i < fieldLength; i++) {
        formFields[i].onfocus = setViewportOnFocus;
        formFields[i].onblur = setViewportOnBlur;
    }
  }
};  

The Simplest Solution

As it turned out, you can prevent the zooming via font size. Yes, you hear me right:

The browser will zoom if the font-size is less than 16px and the default font-size for form elements is 11px (at least in Chrome and Safari).

Here's how you can fix all type of fields. Select field needs :focus pseudo-class. Reference

input[type="color"],
input[type="date"],
input[type="datetime"],
input[type="datetime-local"],
input[type="email"],
input[type="month"],
input[type="number"],
input[type="password"],
input[type="search"],
input[type="tel"],
input[type="text"],
input[type="time"],
input[type="url"],
input[type="week"],
select:focus,
textarea {
  font-size: 16px;
}  

As a result, we just need to ensure the font size for each form element is at least 16px. This by far the most simplest and elegant solution that works pretty well in iOS.

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.