Как отключить масштабирование на мобильной веб-странице с помощью HTML и CSS?
Функция масштабирования не всегда полезна. Одно из неудобств, с которым сталкиваются и разработчики, и пользователи, относится к масштабированию веб-страниц на мобильных устройствах. Мы поможем решить эту проблему. Можно использовать браузер Surefox для отключения этой функции, но все же страница будет масштабироваться при двойном нажатии на экран. Поэтому попробуйте следующие методы, используя HTML и CSS.
1. Как отключить масштабирование с помощью HTML
Самый легкий способ отключения этой функции — это использование HTML тега <meta>. Атрибут user-scalable позволяет увеличить или уменьшить масштаб на мобильном устройстве. Чтобы отключить функцию масштабирования, необходимо задать значение “no” для этого атрибута.
Viewport meta tag
This article describes how to use the «viewport» <meta> tag to control the viewport’s size and shape.
Background
The browser’s viewport is the area of the window in which web content can be seen. This is often not the same size as the rendered page, in which case the browser provides scrollbars for the user to scroll around and access all the content.
Some mobile devices and other narrow screens render pages in a virtual window or viewport, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once. Users can then pan and zoom to see different areas of the page. For example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space.
This is done because not all pages are optimized for mobile and break (or at least look bad) when rendered at a small viewport width. This virtual viewport is a way to make non-mobile-optimized sites in general look better on narrow screen devices.
However, this mechanism is not so good for pages that are optimized for narrow screens using media queries — if the virtual viewport is 980px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques. The viewport meta tag mitigates this problem of virtual viewport on narrow screen devices.
Viewport basics
A typical mobile-optimized site contains something like the following:
Not all devices are the same width; you should make sure that your pages work well in a large variation of screen sizes and orientations.
The basic properties of the «viewport» <meta> tag include:
Controls the size of the viewport. It can be set to a specific number of pixels like width=600 or to the special value device-width , which is 100vw, or 100% of the viewport width. Minimum: 1 . Maximum: 10000 . Negative values: ignored.
Controls the size of the viewport. It can be set to a specific number of pixels like height=400 or to the special value device-height , which is 100vh, or 100% of the viewport height. Minimum: 1 . Maximum: 10000 . Negative values: ignored.
Controls the zoom level when the page is first loaded. Minimum: 0.1 . Maximum: 10 . Default: 1 . Negative values: ignored.
Controls how much zoom out is allowed on the page. Minimum: 0.1 . Maximum: 10 . Default: 0.1 . Negative values: ignored.
Controls how much zoom in is allowed on the page. Any value less than 3 fails accessibility. Minimum: 0.1 . Maximum: 10 . Default: 10 . Negative values: ignored.
Controls whether zoom in and zoom out actions are allowed on the page. Valid values: 0 , 1 , yes , or no . Default: 1 , which is the same as yes . Setting the value to 0 , which is the same as no , is against Web Content Accessibility Guidelines (WCAG).
Specifies the effect that interactive UI widgets, such as a virtual keyboard, have on the page’s viewports. Valid values: resizes-visual , resizes-content , or overlays-content . Default: resizes-visual .
Warning: Usage of user-scalable=no can cause accessibility issues to users with visual impairments such as low vision. WCAG requires a minimum of 2× scaling; however, the best practice is to enable a 5× zoom.
Screen density
Screen resolutions have risen to the size that individual pixels are indistinguishable by the human eye. For example, smartphones often have small screens with resolutions upwards of 1920–1080 pixels (≈400dpi). Because of this, many browsers can display their pages in a smaller physical size by translating multiple hardware pixels for each CSS «pixel». Initially, this caused usability and readability problems on many touch-optimized websites.
On high dpi screens, pages with initial-scale=1 will effectively be zoomed by browsers. Their text will be smooth and crisp, but their bitmap images may not take advantage of the full screen resolution. To get sharper images on these screens, web developers may want to design images – or whole layouts – at a higher scale than their final size and then scale them down using CSS or viewport properties.
The default pixel ratio depends on the display density. On a display with density less than 200dpi, the ratio is 1.0. On displays with density between 200 and 300dpi, the ratio is 1.5. For displays with density over 300dpi, the ratio is the integer floor (density/150dpi). Note that the default ratio is true only when the viewport scale equals 1. Otherwise, the relationship between CSS pixels and device pixels depends on the current zoom level.
Viewport width and screen width
Sites can set their viewport to a specific size. For example, the definition «width=320, initial-scale=1» can be used to fit precisely onto a small phone display in portrait mode. This can cause problems when the browser renders a page at a larger size. To fix this, browsers will expand the viewport width if necessary to fill the screen at the requested scale. This is especially useful on large-screen devices.
For pages that set an initial or maximum scale, this means the width property actually translates into a minimum viewport width. For example, if your layout needs at least 500 pixels of width then you can use the following markup. When the screen is more than 500 pixels wide, the browser will expand the viewport (rather than zoom in) to fit the screen:
Other attributes that are available are minimum-scale , maximum-scale , and user-scalable . These properties affect the initial scale and width, as well as limiting changes in zoom level.
The effect of interactive UI widgets
Interactive UI widgets of the browser can influence the size of the page’s viewports. The most common such UI widget is a virtual keyboard. To control which resize behavior the browser should use, set the interactive-widget property.
Allowed values are:
The visual viewport gets resized by the interactive widget.
The viewport gets resized by the interactive widget.
Neither the viewport nor the visual viewport gets resized by the interactive widget.
When the viewport gets resized, the initial containing block also gets resized, thereby affecting the computed size of viewport units.
Common viewport sizes for mobile and tablet devices
If you want to know what mobile and tablet devices have which viewport widths, there is a comprehensive list of mobile and tablet viewport sizes here. This gives information such as viewport width on portrait and landscape orientation as well as physical screen size, operating system and the pixel density of the device.
С помощью какого мета тега можно запретить пользователю масштабировать страницу
- Что означает тег Viewport?
- Как подключить Viewport для разных устройств
- Как определить разрешение экрана конкретного устройства?
- Где прописать тег Viewport?
- Атрибуты метатега Viewport
- Когда возникла ошибка: значение метатега viewport не задано
- Как проверить адаптирована ли страница под мобильные устройства
Viewport — это область на экране устройства, которая видна пользователю без прокрутки экрана. Представьте страницу, которая нормально отображается на экране ноутбука. Буквы, значки и прочие элементы находятся в оптимальном размере, вам удобно читать текст.
Эта же страница на экране смартфона оказывается совсем неудобной для прочтения. Вам приходится двигать изображения и текст вправо и влево, вниз и вверх. Если задать тег Viewport, веб-страница примет нормальный вид:

На изображении слева страница отображается без тега Viewport, а справа с его помощью задаются параметры отображения. В вариант слева не внедрен адаптивный дизайн сайта и тег Viewport, поетому он не удобен для чтения и пользователь быстрее покинет такой сайт.
При адаптивном дизайне ему будет удобнее читать текст, совершать покупки и переходить между разделами сайта. Чтобы веб-страница отображалась нормально на устройствах с разным разрешением, важно задать правильные настройки тега Viewport.


В таком случае ширина макета экрана не может быть менее 800 пикселей. Если это значение окажется больше, браузер растянет видимую область веб страницы до полного масштаба. Потребность в использовании Viewport появилась после активного распространения смартфонов с высоким разрешением экрана. В них даже адаптированные под мобильные устройства сайты не всегда отображаются правильно.
Например, возьмем для сравнения два смартфона с диагональю 3,5 дюймов, но разной плотностью пикселей. В первом этот показатель составляет до 200 пикселей, а во втором — более 300 пикселей. Одна и та же веб-страница будет выглядеть по-разному на обоих смартфонах, несмотря на одинаковый размер экрана.
В первом смартфоне страница отобразится нормально и будет удобной для чтения, как на мониторе компьютера. Во втором случае из-за высокой плотности пикселей текст отобразится в два раза мельче. Чтобы страницу привести в нормальный вид, ее масштаб необходимо увеличить в два раза. Метатег Viewport может использоваться для адаптивных и неадаптивных версий сайтов.
Еще один параметр — initial-scale — означает коэффициент масштабирования. Если указано значение «1», разрешение CSS и устройства приравниваются друг к другу независимо от размера экрана. Можно указать любое значение параметра от 0.1 до 10.
Мета-тег viewport для адаптивных и неадаптивных шаблонов
Приходилось ли вам сталкиваться с такой ситуацией: заходите вы на страничку интернет-магазина или клиники с мобильного телефона, чтобы посмотреть прайс-лист, а последний столбик в таблице (тот самый, где отображается стоимость) не видно?
В некоторых случаях проблема решается прокруткой вправо, но бывают и ситуации, когда искомую информацию приходится смотреть с компьютера. Чтобы этого не происходило и страницу можно было комфортно просматривать с разных девайсов, и нужен тег viewport.
Понятие о viewport
Viewport ─ это часть страницы, доступная посетителю без прокрутки.
На разных гаджетах из-за отличий в разрешении одна и та же страница может отображаться по-разному. Это не всегда удобно для посетителя:

Чтобы страничка адаптировалась к устройству и контент можно было адекватно просматривать, нужно вставить мета-тег viewport HTML-код сайта.
Прописываем мета-тег viewport
Для этого добавляем определенный код в раздел <head> .
Прописать meta viewport для адаптивных страниц
Им пользуются преимущественно для адаптивных шаблонов. Для этого достаточно прописать одну строчку:
<meta name=»viewport» content=»width=device-width, initial-scale=1″>
- width=device-width делает ширину видимой области такой же, как и ширина экрана гаджета;
- initial-scale отвечает за ее первоначальный масштаб (коэффициент 1 говорит о том, что он равен 100%).
Meta viewport на неадаптивных шаблонах
Не рекомендуется использовать initial-scale, так как изображение страницы будет «съезжать»:

Используем код:
<meta name=»viewport» content=»width=device-width»>
Ширина по умолчанию — 980 пикселей (px). Однако шаблон не всегда соответствует ему. Чтобы это исправить, придется вручную подбирать значение ширины.
-
Если страница выходит за поля девайса справа и слева, используем значение 1024px:
<meta name=»viewport» content=»width=1024″>
<meta name=»viewport» content=»width=720″>
Какие еще параметры есть в meta viewport
Если нужно разрешить или запретить пользователю увеличивать/уменьшать масштаб страницы или вам нужно, чтобы шаблон подстраивался под ориентацию окна, пользуйтесь дополнительными атрибутами:
- minimal-scale ─ минимальный масштаб окна;
- maximal-scale ─ максимальный масштаб окна;
Имеют числовые значения от 0.1 до 10. Значение 1.0 не изменяет масштаб:
<meta name=»viewport» content=»initial-scale=1, maximum-scale=1″>
- user-scalable ─ разрешает или запрещает пользователю изменять масштаб окна;
Имеет значения «yes» и «no» (по умолчанию задано «yes»).
<meta name=»viewport» content=»width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no»>
- orientation ─ управляет ориентацией;
Имеет значения auto (в зависимости от ориентации девайса), landscape (горизонтальная) и portrait (портретная). Auto по умолчанию.
- height ─ отвечает за высоту страницы;
Задается числовое значение от 200 до 10000px, либо устанавливается автоматический подгон под размер экрана с помощью device-height.
Частая ошибка
Некоторые разработчики используют для неадаптивных страниц атрибуты user-scalable=no или initial-scale=1 вместе с maximum-scale=1. Это отключает масштабирование, и посетитель не может увидеть всю страницу.
Пользовались мета-тегом viewport? Пишите отзывы в комментариях!