Disable Auto Zoom in Input "Text" tag - Safari on iPhone
Asked Answered
E

41

884

I made an HTML page that has an <input> tag with type="text". When I click on it using Safari on iPhone, the page becomes larger (auto zoom). Does anybody know how to disable this?

Espadrille answered 7/6, 2010 at 12:6 Comment(10)
For all Twitter Bootstrap users landing here: see also this Github issue.Highminded
I think @daxmacrog answer exactly answers what you want, are you willing to accept it so it can rise to the top and save lots of rework from people reading through all this? 2018 Answer: https://mcmap.net/q/53511/-disable-auto-zoom-in-input-quot-text-quot-tag-safari-on-iphoneCinquefoil
@Cinquefoil the answer you spoke about breaks android pinch and zoom functionality. daxmacrog answer is flawed.Purpurin
I swear, Apple creates these anti-features just to mess with our heads.Shelbashelbi
@AndrewKoster, I agree with you even now in 2020.Popcorn
August 2020, and one more time, I got back here, hoping for a miracle in the answers. See your next year. I am going to eat an apple.Pothook
iOS is next IE.Efficacious
@AndrewKoster I agree with you even now in 2022.Connett
I agree with you even now in 2023.Yellowknife
I agree with you even now in 2024..Counterpunch
P
890

You can prevent Safari from automatically zooming in on text fields during user input without disabling the user’s ability to pinch zoom. Just add maximum-scale=1 but leave out the user-scale attribute suggested in other answers.

It is a worthwhile option if you have a form in a layer that “floats” around if zoomed, which can cause important UI elements to move off screen.

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

Phebe answered 16/9, 2017 at 13:59 Comment(18)
Going to try this. I don't always want 16px size. Sometimes 15 looks good and I still need user to be able to zoom.Konstanz
This works for me on IPhone 6S, IOS 11.2. No zoom on the form field, but can still pinch zoom the page.Glasswork
You can use var iOS = navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); to check whether the browser is on iOSAcetylcholine
This will break android devices zooming abilityGrammar
@Grammar That is good to note, which is why Finesse suggested browser sniffing, but the OP did ask about iOS/Safari specifically.Phebe
@daxmacrog, you are right, but the OP did not mention whether he wants to break androids by allowing needed behaviour. This is where personally I took incorrect option. Of course, it's better to specify.Grammar
@HenrikPetterson This does more than just disabling the auto-zoom as specified by OP, it also disables pinch zoom. So I don't think it's the 2018+ solution.Terr
@AndréWerlang That is not accurate. As stated clearly in the answer, this solution does not disable pinch zoom in Safari (or Firefox), which is what the OP asked about. But as pointed out in previous comments, it does disable user zoom on Android devices and in Chrome on iOS.Phebe
So there's no meta solution for Chrome on iOS. On all mobile iOS browsers it will zoom in automatically, and on mobile Safari you can disable this with maximum-scale=1, but on Chrome for iOS this disables all zooming (like on android) as google thinks it's following standards better, but it's actually worse than Safari because it doesn't let you disable automatic zoom separately from user zoom.Cathepsin
Most accessibility services will also complain about zoom being disabled in any browserUnrestraint
There's a lot of confusion about whether maximum-scale=1 annoyingly disables user pinch zoom. The behavior changed with iOS 10 when Apple rightly decided to ignore disabling user pinch zoom. The good news is that the setting still works to prevent automatic zoom on focus.Dominquedominquez
I think I tried every option and this was the only one that worked to prevent auto-zooming and still allowed user zoom. I can still zoom on android devices as well so maybe things have changed. This seems to be the best solution.Tenenbaum
As @Unrestraint pointed out, disabling zoom is an accessibility issue as many users rely on that to see clearly, especially when the font size is less than 16px as it is in this scenario. Also, just because OP asked for a solution for a problem that was specifically affecting iOS Safari does not indicate that they only support that browser. Who only supports one browser?Easel
Apparently this disables Zoom for Android devices but on the new Iphone X the error still persists.Transhumance
This is not a good answer and even google thinks so: web.dev/meta-viewport/…Undersigned
Just tried this today, since iPhone autozoom is soooo annoying: This change disables autozoom nicely. Pinch zoom still works on iPhone Safari, Edge, Android Browser & PWA. Pinch zom DOES NOT WORK anymore on iPhone PWA installation (which is weird, since this is safari, too?)Iridic
Guys, it seems to me that from a user experience perspective, it's better not to disable auto-zoom. Additionally, when considering accessibility, users with visual impairments may have difficulties recognizing characters, this should also be thought about. In my opinion, it's better to discuss the decision with the designer and move in the direction of increasing the font for the mobile version.Flan
will comment, for those who care, this solution hurts accessibility scores in lighthouse.Apc
C
668

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).

Additionally, the select element needs to have the focus pseudo-class attached.

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;
}

It's not necessary to use all the above, you can just style the elements you need, eg: just text, number, and textarea:

input[type='text'],
input[type='number'],
textarea {
  font-size: 16px;
}

Alternate solution to have the input elements inherit from a parent style:

body {
  font-size: 16px;
}
input[type="text"] {
  font-size: inherit;
}
Costermansville answered 18/6, 2011 at 7:17 Comment(27)
I found this works for those fields specified, but alas not for select fields... any ideas how to achieve similar for these?Brassware
@Brassware For select dropdowns the issue is solved in [#6483925Warrigal
Wonderful! Never imagine this issue is related to font size.Eulalia
Just to get everything covered: select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"] { font-size: 16px; }Lennalennard
Note: The 16px limit will only work if the website is not zoomed (out) by default. If the page (body) is broader than 320 pixels and width=device-width and the page is shown on iPhone in portrait mode, than this will not work.Paduasoy
Why isn't this selected as the best answer? It worked excellent on my iPod touch. This was exactly what I needed. Thanks a lot!Unstressed
I'm on iOS 7 and using Nic Barbier's style – which includes select – Safari still zooms onto select. Any idea?Ordain
@Nic You need to use select:focus. Was having the same issue too.Sassan
I had to use add textarea:focus (might be bootstrap related).Baram
Has anyone succeeded in making this work on an iPhone 6?Tetralogy
don't use a specific px value. Use rem or em instead as the better option: select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"] { font-size: 16px; font-size: 1rem; } though I can't seem to find a good reason why to still target ie7/8Shelled
jonassebastianohlsson.com/blog/2013/11/25/…Verify
I don't understand, how is this a fix? What if I want a smaller/larger font size?Tufts
proper way is to change meta tag to: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>Fleuron
This did not work per say. It was close though. I had to amp up the font size until it stopped zooming in. So it worked, but at the same time, don't automatically think that 16px is the size you want. Tinker with it.Prodigious
@MilosMatic In most cases probably not a good solution, as it completely prevents the user from scaling the page. Potentially even more annoying for your visitors.Vaunting
"Ensure that the browser pinch zoom is not blocked by the page's viewport meta element so that it can be used to zoom the page to 200%. Restrictive values for user-scalable and maximum-scale attributes of this meta element should be avoided." w3.org/TR/mobile-accessibility-mapping/#zoom-magnificationIngate
I had to use select without the focus pseudo-selector to get it to workHypnosis
another way, but this blocks the 2 finger pinch zoom in functionality on android. on iPhone the pinch zoom works fine <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />Ginni
For people struggling with text inputs that don't have type="text" set you can use: input:not([type]), input[type="text"] { font-size: 16px; }Leary
This answer might have worked 7 years ago, but now it is not correct. I have a TEXTAREA with font size 40px, and Safari is auto-zooming it on my iphone 6. The correct answer is @PhebePsalterium
Just keep font-size: initial; for forms elements.Casern
this doesnt work on iOS Safari or Chome, even if i set the font-size of input elements to 16px explicitly...Jorin
I ran into a case with very long option text in a select box triggering this, even with 16px and select:focus. What helps there is option { max-width: 100% } in addition.Visa
Couldn't get the font-size solution to work. The meta maximum-scale=1.0 approach does, but don't want to risk disabling pinch zoom on some devices. Seems to me if the browser is going to automatically zoom in, then it should be courteous enough to automatically zoom out again when the control looses focus. Just my 2c :)Gentile
on my iphone 8 it required 25px to stop zooming. perhaps depends on screen size? would be great to know what the maximum is across all iphonesIlene
This solution is working fine.Korenblat
I
266
@media screen and (-webkit-min-device-pixel-ratio:0) { 
  select:focus,
  textarea:focus,
  input:focus {
    font-size: 16px;
    background: #eee;
  }
}

New: IOS will still zoom, unless you use 16px on the input without the focus.

@media screen and (-webkit-min-device-pixel-ratio:0) { 
  select,
  textarea,
  input {
    font-size: 16px;
  }
}

I added a background since IOS adds no background on the select.

Inclinometer answered 27/4, 2013 at 18:44 Comment(16)
This works not only for safari on iOS (iphone/ipad/ipod), but also Safari/OSX and Chrome (windows and Mac). So if you're trying to specifically target the iphone, this will not work.Entomologize
I just want to say I have lots of different queries using zoom to make development go faster and depending on how much you zoom will determine how much font-size you need I believeExhibitionist
If you don't have an absolute line-height set, or a height on your input element, then won't this cause the element to change size on focus? Why not just set the font styles without the :focus selector?Dryad
This did not work for me using Zurb Foundation. I had to omit the :focus modifier and add !important to the font-size.Plausive
@CiaranPhillips, I think the purpose of the :focus modifiers is to keep the fonts at the normal size when the fields are not selected. It's a great idea, but Safari on iOS 8 still auto-zooms for me unless I remove the :focus modifiers.Seedy
I have the same result with @arlomedia. On iOS 8 limiting to :focus selector will not work.Intermixture
Why is everyone saying 16px but no one cares to mention why exactly is it 16px? Why such an arbitrary number? Why do we have to set our form field text size to 16px and not .. say 1.8rem or 2.5em or such? Is this just a stupid bug from a proprietary OS?Unitarianism
@Unitarianism 100% font size is 16px, that the default for most if not all browsers (desktop too). IOS uses it that as the default probably because it's a comfortable size for reading. Why it is set this way I haven't bothered to look up, don't care.Inclinometer
Use @media screen and (-webkit-min-device-pixel-ratio:0) and (max-device-width:1024px) to limit the effect to iPhone, but do not modify websites when viewed in Chrome.Paduasoy
Watch out: The most recent iOS does not work with the :focus - it will zoom unless the input has 16px without the :focus :(Paduasoy
Updated the answer. For the last year or so, I set base font size 100% and since then, this has not been required.Inclinometer
oddly, if you add width attribute to the input CSS, some zoom is back.Haig
Instead of using a media query, you should use @supports (-webkit-overflow-scrolling: touch), as this css feature only exists on iOSShrewsbury
In case you don't want the not focused select state to have 16px, use transform: scale()Hyperpyrexia
@JamesMoran -webkit-overflow-scrolling support is dropped since iOS 13. Use @supports (-webkit-touch-callout: none) insteadTracitracie
this worked but the other suggestions that aimed to modify meta did notKymry
C
228

If your website is properly designed for a mobile device you could decide not allow scaling.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />

This solves the problem that your mobile page or form is going to 'float' around.

Carricarriage answered 4/12, 2012 at 15:21 Comment(18)
Technically correct, but I disagree with the reasoning. Disabling user zooms on a properly designed site is generally still a bad idea.Bracteate
"Properly designed" is very subjective. Consider a fixed, 50px header at the top of a site that is fully responsive and should work in all browsers. Zooming in iOS Safari breaks the header positioning and pretty much breaks the whole site.Entomologize
Properly designed means that you have taken care of all html (text) and design elements in a way that it is readable on a mobile device (primarily phones). If this is properly done there is no need to allow scaling for a visitor and avoids all the unexpected behaviour when scaling/zooming.Carricarriage
Disabling user zoom capability is a terrible practice from a UX perspective and should really be avoided at all costs. Being able to zoom in freely is a basic accessibility feature, and a control that you should never take away from the user.Interloper
In native mobile apps you never get the chance to zoom and they work just fine, why would a webapp be any different? If you set the appropriate font-size and line-height with clear contrasts you should be ok.Ticklish
It's only an opinion that disabling user scrolling matters. As long as your site works, is readable, etc then you are fine. Native moble apps do not allow you to zoom in and generally speaking most people do not need this feature as long as your app is well built.Loach
@Loach A mobile app can be seen in devices that can range from 320x480 to 1140x2560 as smart phones go and from 600x1024 to 1600x2560 as tablets go (granted most of them report as smaller resolutions), so a webapp that looks good in small screens doesn't necessarily inherit its properties 1:1 in larger ones.Apocopate
Those using the 'it's fine in native apps' argument are overlooking the fact that well-made native apps adhere to OS-level accessibility settings such as text size. Older and badly sighted users can and do use extremely large OS-wide font sizes because they need to. Web apps often don't or can't adhere to this setting, therefore allowing the web-browser's built-in accessibility functionality such as zooming is vital. Whatever you think is perfectly readable, believe me, there are people who won't find it clear enough. Do not take this option away from users if you value usability.Transcendentalistic
@Ticklish xkcd.com/1174 Not being able to zoom is one of the many reasons I avoid mobile apps.Lewin
"Ensure that the browser pinch zoom is not blocked by the page's viewport meta element so that it can be used to zoom the page to 200%. Restrictive values for user-scalable and maximum-scale attributes of this meta element should be avoided." w3.org/TR/mobile-accessibility-mapping/#zoom-magnificationIngate
This is really helpful, as although the 16px works, i needed a way smaller font, thanksCelebes
maximum-scale=1.0 is a very bad idea!Chesson
As suggested in @daxmacrog's answer below, this will work even without user-scalable=0. The auto-zoom then won't take place, but the user can still zoom at will.Glasswork
With this approach you can still pinch zoom the screen, but at least it stops auto-zooming on a field focus.Karnes
Safari ignores the prohibitive zoom meta viewport directives nowadays. It's official. github.com/w3c/html/issues/602Gesundheit
This does not cover every situation: When the font is larger than 16 pixels, Safari may zoom out when focusing an input. In my case I just needed put minimum-scale=1, which also preserves the user's ability to custom zoom.Lemmy
This will be flagged up by Google Lighthouse as an accessibility issue. Use at your own peril.Intendment
This is a terrible idea, don't follow this guy's advice.Misogamy
F
112

Proper way to fix this issue is to change meta viewport to:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>

Important: do not set minimum-scale! This keeps the page manually zoomable.

Fleuron answered 4/12, 2015 at 9:58 Comment(10)
This is not necessarily the "proper" way to prevent this behaviour. Mobile Safari zooms in if the text is deemed too small to read. Switching off zooming all together is heavy handed and prevents users from being able to interact with your page in a way that they may expect.Zinn
Apparently in iOS10 Apple changed the maximum-scale property to not be respected anymore, allowing all sites to zoom in regardless of its setting.Curbing
This works for iOS10 20/September/2016 version... at least works on my app... Thanks!!! Before I was using <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> But I switched it to the line on the response and it worked...Repudiate
"Ensure that the browser pinch zoom is not blocked by the page's viewport meta element so that it can be used to zoom the page to 200%. Restrictive values for user-scalable and maximum-scale attributes of this meta element should be avoided." w3.org/TR/mobile-accessibility-mapping/#zoom-magnificationIngate
I've seen comments how some of these meta tags don't work on iOS 10 and I know that the above works on Chrome for the iOS at least. :) Thanks!Interminable
this worked in ios but in android the pich zoom is not workingSneaking
To disable zoom when the user tap inside a input field... "user-scalable=0" solve my problem.Blume
Sorry for the minus but this is sooo harmful... you shouldn't block scaling and zooming the website as is hurts UX. Disabled people, especially those with seeing issues may be excluded from using your product.Tetralogy
Perhaps you can use javascript to detect if it's iOS and then modify the meta tag accordingly.Cooking
This fix violates web accessibility standards by disabling user scaling.Hylton
A
103

In summary the answer is: set the font size of the form elements to at least 16px

Airframe answered 4/10, 2011 at 23:56 Comment(3)
Yes, this is definetly the best practice to avoid zooming on mobile devices. No js, no hacks, no workarounds at all. But even with 16px I noticed a very little zoom in my pages so I tried 17px, 18px... to see what happens.Unseemly
It is best practice to declare 100% on body, button, input, textarea and select elements. This allows the user to set a default that is not the 16px shipped with browsers. Someone who has trouble reading on screen might set their default to 18px or 20px. You don't want to override their choice by forcing 16px on them. When it comes to iOS, though, they made a decision to scale up any value that their HIG says is too small. Unfortunately it looks like it does not interpret the 100% value, so we are stuck adding in the default to appease it.Infirmary
RE iOS Safari, as of this comment it appears Safari correctly interprets the font-size: 100% value and grabs the 16px necessary.Ellipsis
P
72

As many other answers have already pointed out, this can be achieved by adding maximum-scale to the meta viewport tag. However, this has the negative consequence of disabling user zoom on Android devices. (It does not disable user zoom on iOS devices since v10.)

We can use JavaScript to dynamically add maximum-scale to the meta viewport when the device is iOS. This achieves the best of both worlds: we allow the user to zoom and prevent iOS from zooming into text fields on focus.

| maximum-scale             | iOS: can zoom | iOS: no text field zoom | Android: can zoom |
| ------------------------- | ------------- | ----------------------- | ----------------- |
| yes                       | yes           | yes                     | no                |
| no                        | yes           | no                      | yes               |
| yes on iOS, no on Android | yes           | yes                     | yes               |

Code:

const addMaximumScaleToMetaViewport = () => {
  const el = document.querySelector('meta[name=viewport]');

  if (el !== null) {
    let content = el.getAttribute('content');
    let re = /maximum\-scale=[0-9\.]+/g;

    if (re.test(content)) {
        content = content.replace(re, 'maximum-scale=1.0');
    } else {
        content = [content, 'maximum-scale=1.0'].join(', ')
    }

    el.setAttribute('content', content);
  }
};

const disableIosTextFieldZoom = addMaximumScaleToMetaViewport;

// https://mcmap.net/q/48374/-detect-if-device-is-ios/9039885#9039885
const checkIsIOS = () =>
  /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

if (checkIsIOS()) {
  disableIosTextFieldZoom();
}
Pithecanthropus answered 16/8, 2019 at 15:7 Comment(6)
why you create a copy of addMaximumScaleToMetaViewport? Is it solely for semantic reasons?Jonathonjonati
Yes, just mapping the function to a different name so it's clear how it's being used.Pithecanthropus
Best solution as of today in 2021 (with a bit arranged code)Matteroffact
Continues to be the best solution in 2023!Tellurium
No way, it works!Nochur
This worked great, I refactored it for myself to be slightly easier to read: gist.github.com/pketh/f6b37564b8f42fca7c61eb43c39287deEnigmatic
L
39
input[type='text'],textarea {font-size:1em;}
Lazarolazaruk answered 23/9, 2010 at 22:1 Comment(6)
Note that setting user-scalable to no will disable all zooming, which is probably a bad idea.Lazarolazaruk
This only works if your body font size is the default (un-specified, or 1em, or 100%). If you set a custom font size, you can set the font-size in your snippet to 16px to avoid auto-zooming.Idden
I know this question was directed at iPhone but this is more compatible across platforms and into the future of more platforms/devices, I tried the 16px approach but on an Android tablet only reduced the auto zooming effect. Setting to '1em' as specified in the post solved the issue.Greece
I had a custom font-size (15px), and setting the font-size to 1rem (not em) worked.Dutiful
Neither 1em nor 1rem is a proper solution because both can be less than 16px and Safari requires at least 16px to not zoom.Acetylcholine
this doesnt work on iOS Safari or Chome, even if i set the font-size of input elements to 16px explicitly...Jorin
A
20

Instead of simply setting the font size to 16px, you can:

  1. Style the input field so that it is larger than its intended size, allowing the logical font size to be set to 16px.
  2. Use the scale() CSS transform and negative margins to shrink the input field down to the correct size.

For example, suppose your input field is originally styled with:

input[type="text"] {
    border-radius: 5px;
    font-size: 12px;
    line-height: 20px;
    padding: 5px;
    width: 100%;
}

If you enlarge the field by increasing all dimensions by 16 / 12 = 133.33%, then reduce using scale() by 12 / 16 = 75%, the input field will have the correct visual size (and font size), and there will be no zoom on focus.

As scale() only affects the visual size, you will also need to add negative margins to reduce the field's logical size.

With this CSS:

input[type="text"] {
    /* enlarge by 16/12 = 133.33% */
    border-radius: 6.666666667px;
    font-size: 16px;
    line-height: 26.666666667px;
    padding: 6.666666667px;
    width: 133.333333333%;

    /* scale down by 12/16 = 75% */
    transform: scale(0.75);
    transform-origin: left top;

    /* remove extra white space */
    margin-bottom: -10px;
    margin-right: -33.333333333%;
}

the input field will have a logical font size of 16px while appearing to have 12px text.

I have a blog post where I go into slightly more detail, and have this example as viewable HTML:
No input zoom in Safari on iPhone, the pixel perfect way

Anesthetize answered 1/11, 2018 at 17:35 Comment(0)
V
20

Inspired by @jirikuchta 's answer, I solved this problem by adding this bit of CSS:

#myTextArea:active {
  font-size: 16px; /* `16px` is safer I assume, although `1rem` works too */
}

No JS, and I don't notice any flash or anything.

It's worth noting that a viewport with maximum-scale=1 also works, but not when the page is loaded as an iframe, or if you have some other script modifying the viewport, etc.

Vanlandingham answered 28/10, 2019 at 22:33 Comment(1)
This answer is the holy grailDesperado
G
17

There's no clean way I could find, but here's a hack...

1) I noticed that the mouseover event happens prior to the zoom, but the zoom happens before mousedown or focus events.

2) You can dynamically change the META viewport tag using javascript (see Enable/disable zoom on iPhone safari with Javascript?)

So, try this (shown in jquery for compactness):

$("input[type=text], textarea").mouseover(zoomDisable).mousedown(zoomEnable);
function zoomDisable(){
  $('head meta[name=viewport]').remove();
  $('head').prepend('<meta name="viewport" content="user-scalable=0" />');
}
function zoomEnable(){
  $('head meta[name=viewport]').remove();
  $('head').prepend('<meta name="viewport" content="user-scalable=1" />');
}

This is definitely a hack... there may be situations where mouseover/down don't always catch entries/exits, but it worked well in my tests and is a solid start.

Garvey answered 4/3, 2011 at 16:50 Comment(1)
Not sure when Safari behavior might have changed, but now (iOS6.0.1) mousedown is happening prior to the autozoom. Thus in my prior solution, zooming is getting re-enabled too soon. I haven't come up with an adequate fix, since all events I tried now happen before zoom. You could re-enable zoom upon a keydown or blur, but there are some scenarios that this might miss (such as if user wants to manually zoom before they start typing anything).Garvey
W
16

This worked for me on iOS Safari and Chrome. For the input selector could be set the class or id to enclose the current.

@supports (-webkit-overflow-scrolling: touch) {
   input {
     font-size: 16px;
   }
}
Wiretap answered 27/11, 2020 at 20:57 Comment(2)
It helps, but how?)Alexina
Also worked for me. I just pasted this in index.css and boom, no more janky ios zoom.Life
H
14

I recently (today :D) had to integrate this behavior. In order to not impact the original design fields, including combo, I opted to apply the transformation at the focus of the field:

input[type="text"]:focus, input[type="password"]:focus,
textarea:focus, select:focus {
  font-size: 16px;
}
Haldi answered 18/12, 2012 at 13:24 Comment(3)
FYI, This worked well on my iphone 5 with iOS 6, but on an iphone 4 with iOS 5 in portrait mode, the focus styling was applied after the zoom occurred. Maybe something subtle going on, I didn't investigate further.Horizontal
I just want to say I have lots of different queries using zoom to make development go faster and depending on how much you zoom will determine how much font-size you need I believeExhibitionist
:focus did not work for me iOS 10.2 iPhone 6, but input[type="text"]:hover worked well.Piston
B
13

Add user-scalable=0 to viewport meta as following

<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">

Worked for me :)

Bounded answered 11/10, 2016 at 15:19 Comment(3)
"Ensure that the browser pinch zoom is not blocked by the page's viewport meta element so that it can be used to zoom the page to 200%. Restrictive values for user-scalable and maximum-scale attributes of this meta element should be avoided." w3.org/TR/mobile-accessibility-mapping/#zoom-magnificationIngate
This breaks the rules of accessibility defined by W3.Valley
worked for me, also this is the best solution for me as I want the freedom to change input font sizes below 16px and don't want a JS hackMansour
N
10

I have looked through multiple answers.\

  1. The answer with setting maximum-scale=1 in meta tag works fine on iOS devices but disables the pinch to zoom functionality on Android devices.
  2. The one with setting font-size: 16px; onfocus is too hacky for me.

So I wrote a JS function to dynamically change meta tag.

var iOS = navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
if (iOS)
    document.head.querySelector('meta[name="viewport"]').content = "width=device-width, initial-scale=1, maximum-scale=1";
else
    document.head.querySelector('meta[name="viewport"]').content = "width=device-width, initial-scale=1";
Nuclear answered 6/7, 2020 at 6:32 Comment(0)
N
9

2021 solution...

OK, I've read through all the old answers but none of them worked for me. After many hours of trying different things the solution seemed simple in the end.

input{
    transform: scale(0.875);
    transform-origin: left center;
    margin-right: -14.28%;
}

Tested on iOS/Android/Chrome on PC

This allows you to use a 14px font, if you need a different size then the scaling factor is 14/16 = 0.875 and the negative margin is (1 - 0.875) / 0.875 * 100

My input has a parent set to "display:flex" and it grows to fit the parent because it has "flex: 1 1 auto". You may or may not need this but I'm including it for completeness.

Nellenelli answered 27/9, 2021 at 22:11 Comment(0)
M
8

Javascript hack which is working on iOS 7. This is based on @dlo 's answer but mouseover and mouseout events are replaced by touchstart and touchend events. Basicly this script add a half second timeout before the zoom would enabled again to prevent zooming.

$("input[type=text], textarea").on({ 'touchstart' : function() {
    zoomDisable();
}});
$("input[type=text], textarea").on({ 'touchend' : function() {
    setTimeout(zoomEnable, 500);
}});

function zoomDisable(){
  $('head meta[name=viewport]').remove();
  $('head').prepend('<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0" />');
}
function zoomEnable(){
  $('head meta[name=viewport]').remove();
  $('head').prepend('<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1" />');
} 
Melinite answered 5/11, 2013 at 9:21 Comment(2)
This worked best for me. But, I changed the touchstart/touchend events to one 'focus' event with both zoomDisable and zoomEnable.Kerley
Adding the delay does seem to work pretty well on newer versions of iOS, but it's interesting that it doesn't work very well when set to 250ms. That hints that under some circumstances, 500ms might not work either, but if it works most of the time I guess it's better than not working at all. Good thinking.Garvey
H
8

This worked for me:

input, textarea {
    font-size: initial;
}
Howell answered 2/9, 2014 at 1:0 Comment(2)
Nicely simple, but is there any way to control what that "initial" size is?Histamine
I haven't tested it, but this should be a way to control the font size. (please let me know if this works and I'll update my answer) body { font-size: 20px; } input { font-size: inherit; }Howell
H
8

I used Christina's solution above, but with a small modification for bootstrap and another rule to apply to desktop computers. Bootstrap's default font-size is 14px which causes the zoom. The following changes it to 16px for "form controls" in Bootstrap, preventing the zoom.

@media screen and (-webkit-min-device-pixel-ratio:0) {
  .form-control {
    font-size: 16px;
  }
}

And back to 14px for non-mobile browsers.

@media (min-width: 768px) {
  .form-control {
    font-size: 14px;
  }
}

I tried using .form-control:focus, which left it at 14px except on focus which changed it to 16px and it did not fix the zoom problem with iOS8. At least on my iPhone using iOS8, the font-size has to be 16px before focus for the iPhone to not zoom the page.

Halvah answered 26/9, 2014 at 23:4 Comment(0)
W
7

I did this, also with jQuery:

$('input[type=search]').on('focus', function(){
  // replace CSS font-size with 16px to disable auto zoom on iOS
  $(this).data('fontSize', $(this).css('font-size')).css('font-size', '16px');
}).on('blur', function(){
  // put back the CSS font-size
  $(this).css('font-size', $(this).data('fontSize'));
});

Of course, some other elements in the interface may have to be adapted if this 16px font-size breaks the design.

Wingspread answered 17/12, 2012 at 16:31 Comment(3)
This is classy. This is stylin'. I'm out of puns. Clever approach.Alible
@Curbing did you try on an actual device?Wingspread
This worked for us on iOS 12. I like this approach the best instead of mucking around with css transforms and negative margins.Cantonese
A
7

After a while of while trying I came up with this solution

// set font-size to 16px to prevent zoom 
input.addEventListener("mousedown", function (e) {
  e.target.style.fontSize = "16px";
});

// change font-size back to its initial value so the design will not break
input.addEventListener("focus", function (e) {
  e.target.style.fontSize = "";
});

On "mousedown" it sets font-size of input to 16px. This will prevent the zooming. On focus event it changes font-size back to initial value.

Unlike solutions posted before, this will let you set the font-size of the input to whatever you want.

Adige answered 5/1, 2017 at 14:34 Comment(1)
This one actually works for me, especially since in newer iOS versions you can't use the viewport meta tag to disable zooming.Blamed
D
7

Pseudo elements like :focus don't work as they used to. From iOS 11, a simple reset declaration can be added before your main styles (providing you don't override them with a smaller font size).

/* Prevent zoom */
select, input, textarea {
  font-size: 16px;
}

It's worth mentioning that for CSS libraries such as Tachyons.css then it's easy to accidentally override your font size.

For example class: f5 is equivalent to: fontSize: 1rem, which is fine if you have kept the body font scale at the default.

However: if you choose font size class: f6 this will be equivalent to fontSize: .875rem on a small display upwards. In that instance you'll need to be more specific about your reset declarations:


  /* Prevent zoom */
  select, input, textarea {
    font-size: 16px!important;
  }

@media screen and (min-width: 30em) {

/* not small */

}

Divergency answered 31/3, 2019 at 18:58 Comment(0)
W
7

Using (hover: none) and (pointer: coarse) to target all touchscreen devices:

A number of answers here resort to deploying JavaScript or jQuery.

But it ought to be (and it is) entirely possible to control concerns like conditional font-presentation with CSS.


Safari Mobile requires (with good reason) that any form element, when being interacted with, must have a minimum font-size of 16px (or the visual equivalent).

Let's commit to making that well-thought-out UX apply to all touchscreen browsers.

Then we can adopt the following:

@media only screen and (hover: none) and (pointer: coarse) {

  input,
  select,
  textarea {
    font-size: 11px;
  }

  input:focus,
  select:focus,
  textarea:focus {
    font-size: 16px;
  }
}

The Result

When using a touchscreen device, when any of the interactive form elements above are focused on, the font-size of that form element is temporarily set to 16px.

This, in turn, disables iOS Safari Mobile auto-zoom.

User-initated pinch-zoom remains unaffected on all devices and is never disabled.

Wuhsien answered 31/8, 2022 at 15:34 Comment(0)
C
6

After reading almost every single line here and testing the various solutions, this is, thanks to all who shared their solutions, what I came up with, tested and working for me on iPhone 7 iOS 10.x :

@media screen and (-webkit-min-device-pixel-ratio:0) {
    input[type="email"]:hover,
    input[type="number"]:hover,
    input[type="search"]:hover,
    input[type="text"]:hover,
    input[type="tel"]:hover,
    input[type="url"]:hover,
    input[type="password"]:hover,
    textarea:hover,
    select:hover{font-size: initial;}
}
@media (min-width: 768px) {
    input[type="email"]:hover,
    input[type="number"]:hover,
    input[type="search"]:hover,
    input[type="text"]:hover,
    input[type="tel"]:hover,
    input[type="url"]:hover,
    input[type="password"]:hover,
    textarea:hover,
    select:hover{font-size: inherit;}
}

It has some cons, though, noticeably a "jump" as result of the quick font size change occuring between the "hover"ed and "focus"ed states - and the redraw impact on performance

Cecilycecity answered 9/2, 2017 at 14:54 Comment(1)
Thanks you for your feedback, @MikeBoutin . Can you please share your env (device/iOS version)?Cecilycecity
M
4

I've had to "fix" the auto zoom into form controls issue for a Dutch University website (which used 15px in form controls). I came up with the following set of requirements:

  • user must still be able zoom in
  • font-size must remain the same
  • no flashes of temporary different styling
  • no jQuery requirement
  • must work on newest iOS and not hinder any other OS/device combination
  • if possible no magic timeouts, and if needed correctly clear timers

This is what I came up with so far:

/*
NOTE: This code overrides the viewport settings, an improvement would be
      to take the original value and only add or change the user-scalable value
*/

// optionally only activate for iOS (done because I havn't tested the effect under other OS/devices combinations such as Android)
var iOS = navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
if (iOS)
  preventZoomOnFocus();


function preventZoomOnFocus()
{
  document.documentElement.addEventListener("touchstart", onTouchStart);
  document.documentElement.addEventListener("focusin", onFocusIn);
}


let dont_disable_for = ["checkbox", "radio", "file", "button", "image", "submit", "reset", "hidden"];
//let disable_for = ["text", "search", "password", "email", "tel", "url", "number", "date", "datetime-local", "month", "year", "color"];


function onTouchStart(evt)
{
  let tn = evt.target.tagName;

  // No need to do anything if the initial target isn't a known element
  // which will cause a zoom upon receiving focus
  if (    tn != "SELECT"
      &&  tn != "TEXTAREA"
      && (tn != "INPUT" || dont_disable_for.indexOf(evt.target.getAttribute("type")) > -1)
     )
    return;

  // disable zoom
  setViewport("width=device-width, initial-scale=1.0, user-scalable=0");
}

// NOTE: for now assuming this focusIn is caused by user interaction
function onFocusIn(evt)
{
  // reenable zoom
  setViewport("width=device-width, initial-scale=1.0, user-scalable=1");
}

// add or update the <meta name="viewport"> element
function setViewport(newvalue)
{
  let vpnode = document.documentElement.querySelector('head meta[name="viewport"]');
  if (vpnode)
    vpnode.setAttribute("content",newvalue);
  else
  {
    vpnode = document.createElement("meta");
    vpnode.setAttribute("name", "viewport");
    vpnode.setAttribute("content", newvalue);
  }
}

Some notes:

  • Note that so far I've only tested it on iOS 11.3.1, but will test it on a few other versions soon
  • Use of focusIn events means it requires at least iOS 5.1 (but I see sites we build working in iOS versions older as 9 as a cool bonus anyway)
  • Using event-delegation because a lot of sites I work on have pages which might dynamically create form controls
  • Setting the eventListeners to the html element (documentElement) so as not having to wait for body to become available (don't want to bother checking if document has ready/loaded state or needing to wait for the DOMContentLoaded event)
Mcguire answered 6/7, 2018 at 16:46 Comment(1)
This doesn't work entirely perfect for me (input zoom is triggered for an <input> that is dynamically added when the user pressed a button), but it worked for 85% of my cases, which is good enough at the moment. Just wanted to thank you for sharing your solution!Markle
S
4

Even with these answers it took me three days to figure out what was going on and I may need the solution again in the future.

My situation was slightly different from the one described.

In mine, I had some contenteditable text in a div on the page. When the user clicked on a DIFFERENT div, a button of sorts, I automatically selected some text in the contenteditable div (a selection range that had previously been saved and cleared), ran a rich text execCommand on that selection, and cleared it again.

This enabled me to invisibly change text colors based on user interactions with color divs elsewhere on the page, while keeping the selection normally hidden to let them see the colors in the proper context.

Well, on iPad's Safari, clicking the color div resulted in the on-screen keyboard coming up, and nothing I did would prevent it.

I finally figured out how the iPad's doing this.

It listens for a touchstart and touchend sequence that triggers a selection of editable text.

When that combination happens, it shows the on-screen keyboard.

Actually, it does a dolly zoom where it expands the underlying page while zooming in on the editable text. It took me a day just to understand what I was seeing.

So the solution I used was to intercept both touchstart and touchend on those particular color divs. In both handlers I stop propagation and bubbling and return false. But in the touchend event I trigger the same behavior that click triggered.

So, before, Safari was triggering what I think was "touchstart", "mousedown", "touchend", "mouseup", "click", and because of my code, a text selection, in that order.

The new sequence because of the intercepts is simply the text selection. Everything else gets intercepted before Safari can process it and do its keyboard stuff. The touchstart and touchend intercepts prevent the mouse events from triggering as well, and in context this is totally fine.

I don't know an easier way to describe this but I think it's important to have it here because I found this thread within an hour of first encountering the issue.

I'm 98% sure the same fix will work with input boxes and anything else. Intercept the touch events and process them separately without letting them propagate or bubble, and consider doing any selections after a tiny timeout just to make sure Safari doesn't recognize the sequence as the keyboard trigger.

Sherwoodsherwynd answered 29/8, 2019 at 22:7 Comment(1)
This is a great explanation of what safari is doing. Thanks!Modular
F
3

In Angular you can use directives to prevent zooming on focus on IOS devices. No meta tag to preserve accessibility.

import { Directive, ElementRef, HostListener } from '@angular/core';

const MINIMAL_FONT_SIZE_BEFORE_ZOOMING_IN_PX = 16;

@Directive({ selector: '[noZoomiOS]' })

export class NoZoomiOSDirective {
  constructor(private el: ElementRef) {}

@HostListener('focus')
  onFocus() {
    this.setFontSize('');
  }

@HostListener('mousedown')
  onMouseDown() {
    this.setFontSize(`${MINIMAL_FONT_SIZE_BEFORE_ZOOMING_IN_PX}px`);
  }

private setFontSize(size: string) {
  const { fontSize: currentInputFontSize } = window.getComputedStyle(this.el.nativeElement, null);

  if (MINIMAL_FONT_SIZE_BEFORE_ZOOMING_IN_PX <= +currentInputFontSize.match(/\d+/)) {
      return;
   }

  const iOS = navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
  iOS 
     && (this.el.nativeElement.style.fontSize = size);
 }
}

You can use it like this <input noZoomiOS > after you declare it in your *.module.ts

Fermin answered 5/11, 2018 at 13:47 Comment(0)
C
3

Amazing, there are dozens of answers here with javascript and viewports, and only one other mentions text-size-adjust which is what I believe is the best solution.

You can just set this to none.

Add the following CSS:

* {
 -webkit-text-size-adjust: none;
  text-size-adjust: none;
}
Carpometacarpus answered 14/10, 2020 at 1:46 Comment(7)
this doesn't appear to work on ios, is there more to applying to solution successfully--meaning other requirements such as the meta viewport with appropriate values?Hugmetight
Unfortunately this didn't work for me on safari iOS 14.4Survive
According to developer.mozilla.org text-size-adjust is still considered experimental but supported by current mobile Chrome and Safari. As always, check caniuse.com.Acea
Does this CSS property even have anything to do with auto-zoom? It is meant to control rendered font-size, not screen zoom.Funkhouser
@adam Yes it does. It increases the font size for input boxes and that results in auto zoom.Carpometacarpus
I mean, setting it didn't change anything visually and didn't stop the zooming for me.Funkhouser
@AdamJagosz it definitely worked for me, maybe it depends on your viewport setting as well, it might only work for certain viewportsCarpometacarpus
A
2

Based on Stephen Walsh's answer... This code works without changing the font size of inputs on focus (which looks lame), plus it still works with FastClick, which I suggest adding to all mobile sites to help bring the "snappy". Adjust your "viewport width" to suit your needs.

// disable autozoom when input is focused
    var $viewportMeta = $('head > meta[name="viewport"]');
    $('input, select, textarea').bind('touchend', function(event) {
        $viewportMeta.attr('content', 'width=640, user-scalable=0');
        setTimeout(function(){ $viewportMeta.attr('content', 'width=640, user-scalable=1'); }, 1)
    });
Acea answered 27/6, 2014 at 15:15 Comment(2)
If the user had already zoomed in a bit before clicking the input control, would this solution cause the viewport to suddenly "unzoom"?Sorry
Yes it does, but it doesn't look any more jarring than the previous "zoom" effect that happened every time the user clicked on an input.Shea
A
2

I see people here do some strange stuff with JavaScript or the viewport function and turning off all manually zooming on devices. That shouldn't be a solution in my opinion. Adding this CSS snippet will turn off the auto-zoom in iOS without changing your font-size to a fixed number like 16px.

By default, I use 93.8% (15px) font-size at input fields and by adding my CSS snippet this stays at 93.8%. No need to change to 16px or make it a fixed number.

input[type="text"]:focus,
textarea:focus {
    -webkit-text-size-adjust: 100%;
}
Amplification answered 14/4, 2015 at 0:39 Comment(1)
This doesn’t work for me, tested with both latest iOS 6 and iOS 9.2.1. Here’s a minimal reproducible page: pastebin.com/bh5Zhe9h It still zooms on focus. Strange that this was posted in 2015 and upvoted yet doesn’t work in iOS 6.Rimester
C
2

Setting a font-size (for input fields) equal to the body's font-size, seems to be what prevents the browser from zooming out or in. I'd suggest to use font-size: 1rem as a more elegant solution.

Crossed answered 26/4, 2015 at 11:5 Comment(0)
O
2

By the way, if you use Bootstrap, you can just use this variant:

.form-control {
  font-size: 16px;
}
Octavus answered 1/12, 2017 at 9:40 Comment(0)
C
2

The Simple solution to this problem is:

@media screen and (max-width: 599px) {
  input, select, textarea {
    font-size: 16px;
  }
}

Note: max-width can be customized according to your requirements.

Cantonment answered 6/12, 2022 at 8:0 Comment(1)
This seems to work. I had to use font-size: 16px !important; to override other rules set by a UI component libraryVanpelt
P
1

As the automatical zoom-in (with no zoom-out) is still annonying on iPhone, here's a JavaScript based on dlo's suggestion working with focus/blur.

Zooming is disabled as soon as a text input is fucused and re-anabled when the input is left.

Note: Some users may not apprechiate editing texts in a small text input! Therefore, I personally prefer to change the input's text size during editing (see code below).

<script type="text/javascript">
<!--
function attachEvent(element, evtId, handler) {
    if (element.addEventListener) {
        element.addEventListener(evtId, handler, false);
    } else if (element.attachEvent) {
        var ieEvtId = "on"+evtId;
        element.attachEvent(ieEvtId, handler);
    } else {
        var legEvtId = "on"+evtId;
        element[legEvtId] = handler;
    }
}
function onBeforeZoom(evt) {
    var viewportmeta = document.querySelector('meta[name="viewport"]');
    if (viewportmeta) {
        viewportmeta.content = "user-scalable=0";
    }
}
function onAfterZoom(evt) {
    var viewportmeta = document.querySelector('meta[name="viewport"]');
    if (viewportmeta) {
        viewportmeta.content = "width=device-width, user-scalable=1";
    }
}
function disableZoom() {
    // Search all relevant input elements and attach zoom-events
    var inputs = document.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
        attachEvent(inputs[i], "focus", onBeforeZoom);
        attachEvent(inputs[i], "blur", onAfterZoom);
    }
}
if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
    attachEvent(window, "load", disableZoom);
}
// -->
</script>

The following code will change an input's text size to 16 pixel (calculated, i.e., in the current zoom size) during the element has the focus. iPhone will therefore not automatically zoom-in.

Note: The zoom factor is calculated based on window.innerWidth and iPhone's display with of 320 pixels. This will only be valid for iPhone in portrait mode.

<script type="text/javascript">
<!--
function attachEvent(element, evtId, handler) {
    if (element.addEventListener) {
        element.addEventListener(evtId, handler, false);
    } else if (element.attachEvent) {
        var ieEvtId = "on"+evtId;
        element.attachEvent(ieEvtId, handler);
    } else {
        var legEvtId = "on"+evtId;
        element[legEvtId] = handler;
    }
}
function getSender(evt, local) {
    if (!evt) {
        evt = window.event;
    }
    var sender;
    if (evt.srcElement) {
        sender = evt.srcElement;
    } else {
        sender = local;
    }
    return sender;
}
function onBeforeZoom(evt) {
    var zoom = 320 / window.innerWidth;
    var element = getSender(evt);
    element.style.fontSize = Math.ceil(16 / zoom) + "px";
}
function onAfterZoom(evt) {
    var element = getSender(evt);
    element.style.fontSize = "";
}
function disableZoom() {
    // Search all relevant input elements and attach zoom-events
    var inputs = document.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
        attachEvent(inputs[i], "focus", onBeforeZoom);
        attachEvent(inputs[i], "blur", onAfterZoom);
    }
}
if (navigator.userAgent.match(/iPhone/i)) {
    attachEvent(window, "load", disableZoom);
}
// -->
</script>
Paduasoy answered 14/7, 2013 at 13:13 Comment(0)
B
0

It took me a while to find it but here's the best code that I found......http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/

var $viewportMeta = $('meta[name="viewport"]');
$('input, select, textarea').bind('focus blur', function(event) {
$viewportMeta.attr('content', 'width=device-width,initial-scale=1,maximum-scale=' +        (event.type == 'blur' ? 10 : 1));
});
Birthright answered 6/6, 2014 at 15:10 Comment(0)
P
0

A comment for the top answer about setting font-size to 16px asked how that is a solution, what if you want bigger/smaller font.

I don't know about you all, but using px for font sizes is not the best way to go, you should be using em.

I ran into this issue on my responsive site where my text field is larger than 16 pixels. I had my form container set to 2rem and my input field set to 1.4em. In my mobile queries I change html font-size depending on the viewport. Since the default html is 10, my input field calculates to 28px on desktop

To remove the auto-zoom I had to change my input to 1.6em. This increased my font size to 32px. Just slightly higher and hardly noticeable. On my iPhone 4&5 I change my html font-size to 15px for portrait and back to 10px for landscape. It appeard that the sweet spot for that pixel size was 48px which is why I changed to from 1.4em (42px) to 1.6em (48px).

The thing you need to do is find the sweet spot on font-size and then convert it backwards in your rem/em sizes.

Pairoar answered 26/5, 2016 at 17:41 Comment(2)
For future readers: Nobody should ever use em, since it opens up pandora's box. Nobody just changes the font size without redesigning the page anyways, since a lot of layouts can be broken by that. For increased font size of the OS all browsers naturally scale up to the base of 16, making rem obsolete since px thus behaves the same but is WAY easier to handle. Otherwise you would be in trouble with mixing your rem with px by plugins anyway.Emilio
@Emilio your comment saying "Nobody should ever use em" is a personal comment. If someone learns to use em and rem correctly, then it makes scaling a website to devices much easier. px and pt are fixed so if you have your site responsive, you need media queries all over the place for every font that needs changing. If you use rem and em correctly, your media query is just on the html font-size and everything else scales correctly.Pairoar
C
0

Here is a hack I used on one of my projects:

select {
    font-size: 2.6rem; // 1rem = 10px
    ...
    transform-origin: ... ...;
    transform: scale(0.5) ...;
}

Ended up with the initial styles and scale I wanted but no zoom on focus.

Cochran answered 1/8, 2018 at 15:23 Comment(0)
W
0

Recently ran into this using Bootstrap 5.3 .input-group-sm containing .form-control. Resolved using only the following CSS (no viewport or script hacks)...

input, textarea {
    font-size: 1rem !important;
}
@media (min-width: 768px) {
    input, textarea {
        font-size: inherit !important;
    }
}

That should make the font large enough to avoid auto-zoom on small devices. Increase the min-width media breakpoint as needed for tablets (none were available for testing).

Wellhead answered 12/9, 2023 at 13:33 Comment(0)
C
0

For android and iOS, the solution is different. If we put maximum-scale=1, then it will stop zoom in capability of android device but on iOS device, it works expected. Add this solution to solve this in react application (In index.js file)

// Detect the device OS
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);

// Set viewport properties based on the device OS
const viewportContent = isIOS
    ? 'width=device-width, initial-scale=1, maximum-scale=1'
    : 'width=device-width, initial-scale=1, shrink-to-fit=no';

// Create a meta tag and append it to the document head
const metaTag = document.createElement('meta');
metaTag.name = 'viewport';
metaTag.content = viewportContent;
document.head.appendChild(metaTag);
Cortez answered 14/12, 2023 at 6:32 Comment(0)
R
-3

Please do not use Javascript or hacks to make it work. That will affect your project score on the web.

This will do the trick:

input, input:active, input:focus, input:focus-within, input:hover, input:visited {
    font-size: 16px!important;
}
Robi answered 9/12, 2018 at 20:13 Comment(3)
How is this not a hack? Unless you happen to want all your inputs font size at 16px then this will screw up the look/layout of the site. Not a proper solution at all.Adelbert
This is a perfect solution for the question. You are a bit too premature with your answer to my solution. Read the question good first. Why would he/she not want all inputs zoom fixed? Isn't that strange? So you are going to solve a zoom input on a page and not on another page?Robi
The point is you are "solving" one problem by introducing another--being forced to have every input use 16px for the font size. What if your inputs were sized smaller or larger (as is frequently going to be the case)? My primary criticism is that you are calling out other people for using "hacks", but all this does is force all inputs to a fixed font size to work around the issue (which by the way was already pointed out by the top rated answer 7 years ago). Maybe you should read the many other answers first.Adelbert
K
-13

IT'S WORK!!! I FINISH MY SEARCH JOURNEY!

<meta name="viewport" content="width=640px, initial-scale=.5, maximum-scale=.5" />

tested on iPhone OS6, Android 2.3.3 Emulator

i have a mobile website that has a fixed width of 640px, and i was facing the autozoom on focus to.

i was trying allot of slutions but none was working on both iPhone and Android!

now for me it's ok to disable the zoom because the website was mobile-first design!

this is where i find it: How to do viewport sizing and scaling for cross browser support?

Kalgoorlie answered 14/5, 2014 at 9:49 Comment(3)
This does some very nasty stuff to the view size, like not letting accessible people zoom. I don't think this is a good solution?Cooperative
Yea, this solution is generally not great because it fixes the viewport size and caused issues as you migrate to different devices.Egidio
Out of standards.Casern

© 2022 - 2025 — McMap. All rights reserved.