Html meta user scale

Использование мета тега viewport в неадаптивных шаблонах

Нет сомнения, что вы используете мета тег viewport при работе с адаптивными шаблонами. Но знаете ли вы, что мета тег viewport может быть полезен и для неадаптивных шаблонов? Если у вас нет времени для конвертации шаблона своего проекта в адаптивный, то следует прочесть материалы данного урока, чтобы использовать мета тег viewport для улучшения вида вашего дизайна на мобильных устройствах.

Обычное использование мета тега viewport

Обычно мета тег viewport используется для установки ширины и начального масштаба для окна просмотра на мобильных устройствах. Вот пример.

Использование мета тега viewport в неадаптивном шаблоне

По умолчанию ширина окна просмотра на iPhone устанавливается равной 980px. Но ваш дизайн может плохо соответствовать данному диапазону. Значение может быть для шаблона слишком большим или маленьким. Ниже приводится два примера. которые используют мета тег viewport для улучшения внешнего вида неадаптивного шаблона на мобильных устройствах.

Пример

Посмотрите на сайт Themify с мобильного устройства.

Искажения шаблона на мобильном устройстве

Левый снимок экрана демонстрирует внешний вид сайта без использования мета тега viewport . Можно заметить, что страница касается обеих сторон экрана. Если добавить мета тег viewport с указанием ширины 1024px, то будет оставаться зазор слева и справа.

Читайте также:  Laravel required php extensions

Другой пример

Если ваш дизайн слишком узкий, то он тоже будет выглядеть коряво. Допустим, ширина контейнера 700px и он не адаптируется. В таком случае внешний вид будет как ниже приведенном слева снимке экрана — широкая белая полоса слева.

Узкий неадптивный шаблон

Проблему легко устранить установив ширину окна просмотра 720px. Ширина дизайна не изменяется, но мобильное устройство будет масштабировать его до 720px.

Общая ошибка

Общая ошибка заключается в том, что разработчики часто используют значение initial-scale=1 для неадптивных шаблонов. Такая установка приводит к отрисовке 100% страницы без масштабирования. Если дизайн неадаптивный, то пользователю приходится либо много прокручивать, либо вручную устанавливать масштаб, чтобы увидеть всю страницу. Самый плохой случай — сочетание user-scalable=no или maximum-scale=1 с initial-scale=1 . Таким образом отключается возможность масштабирования на сайте. А без масштабирования нет возможности увидеть всю страницу. Если ваш шаблон не адаптивный,не отключайте масштабирование и не сбрасывайте начальный масштаб!

Отключение масштабирования

Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: webdesignerwall.com/tutorials/viewport-meta-tag-for-non-responsive-design
Перевел: Сергей Фастунов
Урок создан: 10 Октября 2012
Просмотров: 269873
Правила перепечатки

5 последних уроков рубрики «CSS»

Забавные эффекты для букв

Реализация забавных подсказок

Небольшой концепт забавных подсказок, которые реализованы на SVG и anime.js. Помимо особого стиля в примере реализована анимация и трансформация графических объектов.

Анимированные буквы

Солнцезащитные очки от первого лица

Прикольный эксперимент веб страницы отображение которой осуществляется “от первого лица” через солнцезащитные очки.

Источник

Вёрстка: Мета-теги для адаптивной вёрстки

Мета-тег viewport определяет параметры (шиирина, высота, масштаб по-умолчанию и возможный) области, которую видит пользователь на экране, когда заходит на страницу сайта с любого устройства.

# viewport - основной мета тег для адаптивности 

Мета-тег viewport

Атрибут width определяет ширину области просмотра в пикселях (от 200 до 10000) или равной ширине страницы в соответствии с размером экрана (константа device-width).

Если значение не задано, по умолчанию устанавливается – в мобильном Safari = 980px, Opera = 850px, Android WebKit = 800px, IE = 974px

Атрибут height определяет высоту области просмотра в пикселях (от 233 до 10000 пикселей) или равной высоте страницы в соответствии с размером экрана (константа device-height).

Атрибут initial-scale определяет начальный масштаб страницы в единицах от 0.1 до 1.0

Атрибут user-scalable определяет доступность масштабирования страницы пользователем

Атрибут minimum-scale определяет минимальный масштаб области просмотра в единицах от 0.1 до 1.0

Атрибут maximum-scale определяет максимальный масштаб области просмотра в единицах от 0.1 до 1.0

Атрибут shrink-to-fit используется для указания, может ли страница уменьшаться в размере, чтобы поместиться на экране мобильного устройства, если ширина контента превышает ширину экрана.

Когда атрибут shrink-to-fit установлен в значение yes, страница может быть уменьшена в размере так, чтобы все ее содержимое поместилось на экране мобильного устройства. Если же атрибут установлен в значение no, то страница не будет уменьшаться в размере, даже если ее содержимое превышает ширину экрана, и пользователь должен будет использовать горизонтальную прокрутку, чтобы просмотреть всю страницу.

 // для приведённого примера: установить ширину области просмотра равной ширине экрана, изначально не масштабировать страницу, запретить пользователю масштабировать страницу

Мета-тег X-UA-Compatible

Мета-тег указывает только для IE (до 11 версии) наиболее совместимый режим работы: edge

Атрибут chrome=1 устарел с 2014 года.

В целом этот мета-тег устарел.

Мета-тег HandheldFriendly

Мeta-тег определяет оптимизирована ли страница сайта под мобильные устройства на Palm и Blackberry (в браузере AvantGo)

Распознаётся многими другими мобильными браузерами.

В целом этот мета-тег устарел, но используется по инерции.

Мета-теги для Apple устройств

Устанавливает, будет ли веб-приложение работать в полноэкранном режиме.

Код был обновлён. Предыдущий рейтинг:

Комментарии

Ничего лишнего — только сниппеты на developer.donnoval.ru

2013-2023 © «Полезный код» | developer.donnoval.ru

Источник

Viewport meta tag

This article describes how to use the «viewport» 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:

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

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» 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:

meta name="viewport" content="width=500, initial-scale=1" /> 

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.

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.

Specifications

See also

Found a content problem with this page?

This page was last modified on Jul 5, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью