Мета тег для мобильных устройств. Что такое Viewport, как он работает и для чего вообще нужен

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

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

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

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

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

Пример

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

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

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

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

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

Общая ошибка

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

Создадим простую страничку с минимальной разметкой:

Hello world!

Hello world!

Теперь откроем эту страничку на мобильном устройстве. Открыв, увидим, что наша страница отобразится примерно таким образом:

Как видно, текст слишком мелкий для чтения, есть куча пустого пространства, и для того, чтобы прочесть этот текст, нам нужно его увеличивать приближением.

Почему же так происходит?

Проблема мобильных браузеров

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

Если подумать логически, то в этом есть смысл: мобильный браузер видит страницу и предполагает, что она создана для десктопной версии браузера, что верно для подавляющего числа сайтов. Исходя из этого, этот браузер задает странице ширину 980px (Safari iPhone) и пытается оптимально уместить ее на экране смартфона, отобразив в максимально уменьшенном масштабе. Обычно ширина сайтов примерно такой и является, поэтому открыв среднестатистическую веб-страницу на мобильном устройстве, она растянется на всю свою ширину, но меньше в 2-3 раза своего оригинального размера.

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

И вот как раз для этого мы и будем использовать мета-тег viewport , который был введен компанией Apple и как обычно скопирован остальными.

Добавим в блок следующую строку:

И вот что получится в результате:

Совсем другое дело. Задав мета-тегу viewport значение “device-width” , мы говорим браузеру, что ширина области просмотра равняется ширине этого устройства, а не стандартной ширине в 980px, как он может предполагать по-умолчанию. На большом количестве смартфонов ширина экрана равняется 320px (в портретном режиме). Можно задать самостоятельно ширину в 320px, что даст тот же результат, но на некоторых смартфонах ширина экрана может быть другой, поэтому самый оптимальный вариант — использовать device-width.

Одним из самых распространенных вариантов определения области просмотра является следующий вариант:

который определяет ширину страницы и задает начальный масштаб.

Также, часто можно встретить такой вариант:

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

Мета-тег viewport — относительно новый, поэтому на данный момент поддерживается не всеми браузерами, особенно это касается старых моделей смартфонов. В таких случаях есть смысл использовать некоторые старые методы, которые позволяют браузеру идентифицировать страничку, как оптимизированную под мобильный веб. Это можно сделать, с помощью следующий мета-тегов:

Подробнее об этих и других специфических мобильных тегах можно почитать .

Возможные параметры для мета-тега viewport

Атрибут Возможное значение Описание
width
(от 200px — 10,000px)
или константа device-width.
Определяет ширину viewport.
Если ширине не указана, в мобильном Safari устанавливается значение 980px, в Opera - 850px, в Android WebKit - 800px, а в IE - 974px.
height Целое неотрицательное значение
(от 223px до 10,000px)
или константа deviceheight
Определяет высоту viewport. В большинстве случаев на этот атрибут можно не обращать внимание
initial-scale
Значение 1.0 - не масштабировать
Определяет начальный масштаб страницы. Чем больше число, тем выше масштаб.
user-scalable no или yes Определяет, может ли пользователь изменять масштаб в окне.
По-умолчанию “yes” в мобильном Safari.
minimum-scale Число с точкой (от 0.1 до 10).
1.0 - не масштабировать
Определяет минимальный масштаб viewport. По-умолчанию “0.25” в мобильном Safari.
maximum-scale Число с точкой (от 0.1 до 10).
1.0 - не масштабировать
Определяет максимальный масштаб viewport. По-умолчанию “1.6” в мобильном Safari.

Таблица совместимости с viewport

Два вьюпорта

Итак, допустим, что вьюпорт слишком узок для нашего CSS-шаблона. Очевидное решение - сделать вьюпорт шире. Однако, для начала разделим понятие вьюпорта на две части: визуальный вьюпорт и вьюпорт страницы.

Очень неплохо концепцию вьюпортов объясняет Джордж Камминс (George Cummins) на Stack Overflow :

Представьте вьюпорт страницы как большое изображение с неизменными размерами и формой. Теперь представьте меньшую по размеру рамку, через которую вы смотрите на это большое изображение. Эта рамка окружена непроницаемым материалом, который не дает вам увидеть большое изображение полностью, за исключением отдельных его частей. Часть большого изображения, которая видна через рамку, и будет визуальным вьюпортом. Если отойти с рамкой от большого изображения (zoom out, т.е. уменьшить масштаб), то можно увидеть сразу все изображение, или же подойти поближе (zoom in, увеличить масштаб), тогда можно будет рассмотреть только часть изображения. Также, можно поворачивая рамку менять ее ориентацию (на портретную или ландшафтную), при этом размер и форма большого изображения (вьюпорта страницы) всегда остается неизменной.

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

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

Таким образом, -элемент изначально принимает ширину вьюпорта страницы и дальше CSS ведет себя так, если бы экран был намного шире экрана телефона. Это обеспечивает сайту такое же поведение, как и в десктопном браузере.

Какой же ширины сам визуальный вьюпорт? Это зависит от браузера. Safari iPhone использует 980px, Opera - 850px, Android WebKit - 800px, а IE - 974px.

Некоторые браузеры ведут себя по-своему:

Symbian WebKit пытается приравнять вьюпорт страницы к визуальному вьюпорту, и это означает, что элементы с процентной шириной могут вести себя непредсказуемо. Однако, если страница не умещается в визуальном вьюпорте из-за абсолютных величин браузер растягивает вьюпорт страницы максимум до 850-ти пикселей.

Samsung WebKit делает вьюпорт страницы равным по ширине самого широкого элемента.

На BlackBerry при масштабе в 100% вьюпорт страницы равен будет визуальному вьюпорту при любых раскладах.

Масштабирование (Zooming)

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

Понимание вьюпорта страницы

Для лучшего понимания размеров вьюпорта страницы следует взглянуть на то, что происходит при наименьшем возможном масштабе страницы. Большинство мобильных браузеров по-умолчанию отображают любую страницу в наименьшем масштабе.

Дело в том, что размеры вьюпорта страницы браузеров полностью совпадают с экраном при максимально уменьшенном масштабе и поэтому равны визуальному вьюпрту.

Таким образом, ширина и высота вьюпорта страницы равна всему тому, что отображено на экране при наименьшем масштабе. При увеличении масштаба пользователем эти размеры остаются неизменными.

Ширина вьюпорта страницы всегда неизменна. Если изменить ориентацию экрана смартфона, визуальный вьюпорт изменится, но в то же время мобильный браузер приспособится к новой ориентации, немного увеличив масштаб таким образом, что вьюпорт страницы снова станет таким же по ширине, как и визуальный вьюпорт.


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


Android и target-densitydpi

У устройств на платформе андроид есть свой атрибут для viewport, который выключает масштабирование для дисплеев с различным разрешением.

На устройствах с HDPI (240dpi) не будет масштабирования.

Такая запись означает, что не будет масштабирования ни на каком из устройств на Андроиде.

Материал взят с сайта:

Так уж сложилось, что мобильные браузеры появились сравнительно недавно, а сайтов в сети к тому времени уже было огромное количество. Естественно, все эти сайты совсем не были оптимизированы под маленькие экраны смартфонов, а смартфоны в свою очередь, вынуждены были полагать, что все сайты в ширину занимают где-то около 1000px (980px в сафари). Нужно было как-то решать сложившуюся ситуацию и в apple придумали метатег , который по традиции потом сперли все остальные производители браузеров.

Давайте рассмотрим типично-эпичную верстку сайта:

html

Hello world

Hello world

Откроем его в мобильном браузере. Вот что мы увидим:

Как вы правильно заметили, текст слишком мелкий и произошло это потому, что сафари попытался вместить наш сайт (который по его предположению сделан для браузеров с шириной экрана около 980pх)

Давайте теперь сообщим браузеру, что наш сайт адаптирован для любой ширины экрана.

html

Что получилось:

Ну вот, теперь все намного лучше. Обозначив width=device-width , мы сказали браузеру, что нам нужна область просмотра контента, равная ширине экрана мобильного устройства.

Можно вручную задать значение для width. Например content="width=320px" , но этого не рекомендуется делать, потому-что различные смартфоны могут иметь абсолютно различную ширину экрана.

Очень распространенным вариантом является:

html

такой вариант задает ширину страницы и начальный масштаб (в данном случае без масштабирования)

Также часто используется следующий вариант:

html

Такие значения используют в случае, если сайт будет использоваться и функционировать как мобильное приложение. Т.е

  1. при загрузке страницы она не будет смасштабирована
  2. страница займет всю ширину мобильного браузера
  3. запрещено любое пользовательское масштабирование
  4. доступен только горизонтальный и вертикальный скролл

Используйте эту конфигурцию, только в том случае, если знаете, что делаете.

Давайте разберем допустимые параметры и их значения, доступные в мета теге viewport

width

Целое число (от 200px - 10,000px) или “device-width”.

Задает ширину viewport. Если нирина viewport не указана, то:

  • для мобильного Safari это 980px
  • Opera - 850px
  • Android WebKit - 800px
  • IE - 974px

height

Целое число (от 223px до 10,000px) или “device-height”

задает высоту viewport. 99% случаев, просто не обращайте внимания на этот параметр, но если сильно надо – пробуйте и экспериментируйте. Удачи..

initial-scale

1.0 - не масштабировать. Задает масштаб страницы. Увеличиваем значение – увеличиваем масштаб.

user-scalable

Доступные значения no или yes

Задает возможнось изменения масштаба страницы. По-умолчанию установлено как yes в Safari.

minimum-scale и maximum-scale

Доступные значения (от 0.1 до 10).

1.0 - не масштабировать. Определяет минимальный и максимальный масштаб viewport соответственно.

По-умолчанию в мобильном Safari minimum-scale = "0.25" , maximum-scale = “1.6”.

Совет: Не используйте мета-теги (в том числе и этот), пока не разобрались, зачем все это нужно. И тестируйте все в различных мобильных браузерах. Удачи!

Can’t make the #ChromeDevSummit this year? Catch all the content (and more!) on the livestream, or join your peers for a CDS Extended event at a hosted location nearby. To learn more, check out the Chrome Dev Summit 2019 website .

Responsive Web Design Basics

Pete is a Developer Advocate

The use of mobile devices to surf the web is growing at an astronomical pace, but unfortunately much of the web isn"t optimized for those mobile devices. Mobile devices are often constrained by display size and require a different approach to how content is laid out on the screen.

A multitude of different screen sizes exist across phones, "phablets," tablets, desktops, game consoles, TVs, and even wearables. Screen sizes are always changing, so it"s important that your site can adapt to any screen size, today or in the future.

Set the viewport

Pages optimized for a variety of devices must include a meta viewport tag in the head of the document. A meta viewport tag gives the browser instructions on how to control the page"s dimensions and scaling.

TL;DR

  • Use the meta viewport tag to control the width and scaling of the browser"s viewport.
  • Include width=device-width to match the screen"s width in device-independent pixels.
  • Include initial-scale=1 to establish a 1:1 relationship between CSS pixels and device-independent pixels.
  • Ensure your page is accessible by not disabling user scaling.

To attempt to provide the best experience, mobile browsers render the page at a desktop screen width (usually about 980px, though this varies across devices), and then try to make the content look better by increasing font sizes and scaling the content to fit the screen. This means that font sizes may appear inconsistent to users, who may have to double-tap or pinch-to-zoom in order to see and interact with the content.

Using the meta viewport value width=device-width instructs the page to match the screen"s width in device-independent pixels. This allows the page to reflow content to match different screen sizes, whether rendered on a small mobile phone or a large desktop monitor.

Some browsers keep the page"s width constant when rotating to landscape mode, and zoom rather than reflow to fill the screen. Adding the attribute initial-scale=1 instructs browsers to establish a 1:1 relationship between CSS pixels and device-independent pixels regardless of device orientation, and allows the page to take advantage of the full landscape width.

Note: To ensure that older browsers can properly parse the attributes, use a comma to separate attributes.

Ensure an accessible viewport

In addition to setting an initial-scale , you can also set the following attributes on the viewport:

  • minimum-scale
  • maximum-scale
  • user-scalable

When set, these can disable the user"s ability to zoom the viewport, potentially causing accessibility issues.

Size content to the viewport

On both desktop and mobile devices, users are used to scrolling websites vertically but not horizontally; forcing the user to scroll horizontally or to zoom out in order to see the whole page results in a poor user experience.

TL;DR

  • Do not use large fixed width elements.
  • Content should not rely on a particular viewport width to render well.
  • Use CSS media queries to apply different styling for small and large screens.

When developing a mobile site with a meta viewport tag, it"s easy to accidentally create page content that doesn"t quite fit within the specified viewport. For example, an image that is displayed at a width wider than the viewport can cause the viewport to scroll horizontally. You should adjust this content to fit within the width of the viewport, so that the user does not need to scroll horizontally.

Since screen dimensions and width in CSS pixels vary widely between devices (for example, between phones and tablets, and even between different phones), content should not rely on a particular viewport width to render well.

Setting large absolute CSS widths for page elements (such as the example below), cause the div to be too wide for the viewport on a narrower device (for example, a device with a width of 320 CSS pixels, such as an iPhone). Instead, consider using relative width values, such as width: 100% . Similarly, beware of using large absolute positioning values that may cause the element to fall outside the viewport on small screens.

Use CSS media queries for responsiveness

Media queries are simple filters that can be applied to CSS styles. They make it easy to change styles based on the characteristics of the device rendering the content, including the display type, width, height, orientation, and even resolution.

TL;DR

  • Use media queries to apply styles based on device characteristics.
  • Use min-width over min-device-width to ensure the broadest experience.
  • Use relative sizes for elements to avoid breaking layout.

For example, you could place all styles necessary for printing inside a print media query:

In addition to using the media attribute in the style sheet link, there are two other ways to apply media queries that can be embedded in a CSS file: @media and @import . For performance reasons, either of the first two methods are recommended over the @import syntax (see Avoid CSS imports).

@media print { /* print style sheets go here */ } @import url(print.css) print;

The logic that applies to media queries is not mutually exclusive, and for any filter meeting that criteria the resulting CSS block is applied using the standard rules of precedence in CSS.

Apply media queries based on viewport size

Media queries enable us to create a responsive experience where specific styles are applied to small screens, large screens, and anywhere in between. The media query syntax allows for the creation of rules that can be applied depending on device characteristics.

@media (query) { /* CSS Rules used when query matches */ }

While there are several different items we can query on, the ones used most often for responsive web design are min-width , max-width , min-height , and max-height .

Parameters
min-width Rules applied for any browser width greater than the value defined in the query.
max-width Rules applied for any browser width less than the value defined in the query.
min-height Rules applied for any browser height greater than the value defined in the query.
max-height Rules applied for any browser height less than the value defined in the query.
orientation=portrait Rules applied for any browser where the height is greater than or equal to the width.
orientation=landscape Rules for any browser where the width is greater than the height.
  • When the browser is between 0px and 640px wide, max-640px.css is applied.
  • When the browser is between 500px and 600px wide, styles within the @media is applied.
  • When the browser is 640px or wider , min-640px.css is applied.
  • When the browser width is greater than the height , landscape.css is applied.
  • When the browser height is greater than the width , portrait.css is applied.

A note on min-device-width

It is also possible to create queries based on min-device-width , though this practice is strongly discouraged .

The difference is subtle but very important: min-width is based on the size of the browser window whereas min-device-width is based on the size of the screen. Unfortunately some browsers, including the legacy Android browser, don"t report the device width properly; they report the screen size in device pixels instead of the expected viewport width.

In addition, using min-device-width can prevent content from adapting on desktops or other devices that allow windows to be resized because the query is based on the actual device size, not the size of the browser window.

Use any-pointer and any-hover for flexible interactions

Starting with Chrome 39, your style sheets can write selectors that cover multiple pointer types and hover behaviors. The any-pointer and any-hover media features are similar to pointer and hover in that they allow you to query the capabilities of the user"s pointer. However, unlike the latter, any-pointer and any-hover operate on the union of all pointer devices rather than just the primary pointer device.

Use relative units

A key concept behind responsive design is fluidity and proportionality as opposed to fixed width layouts. Using relative units for measurements can help simplify layouts and prevent accidental creation of components that are too big for the viewport.

For example, setting width: 100% on a top level div , ensures that it spans the width of the viewport and is never too big or too small for the viewport. The div fits, no matter if it"s a 320px wide iPhone, 342px wide Blackberry Z10, or a 360px wide Nexus 5.

In addition, using relative units allows browsers to render the content based on the user"s zoom level without the need for adding horizontal scroll bars to the page.

Not recommended —fixed width

Recommended —responsive width

Div.fullWidth { width: 100%; }

How to choose breakpoints

Don"t define breakpoints based on device classes. Defining breakpoints based on specific devices, products, brand names, or operating systems that are in use today can result in a maintenance nightmare. Instead, the content itself should determine how the layout adjusts to its container.

TL;DR

  • Create breakpoints based on content, never on specific devices, products, or brands.
  • Design for the smallest mobile device first; then progressively enhance the experience as more screen real estate becomes available.
  • Keep lines of text to a maximum of around 70 or 80 characters.

Pick major breakpoints by starting small, then working up

Preview of the weather forecast displayed on a small screen.

Design the content to fit on a small screen size first, then expand the screen until a breakpoint becomes necessary. This allows you to optimize breakpoints based on content and maintain the least number of breakpoints possible.

Let"s work through the example we saw at the beginning: the weather forecast. The first step is to make the forecast look good on a small screen.


Next, resize the browser until there is too much white space between the elements, and the forecast simply doesn"t look as good. The decision is somewhat subjective, but above 600px is certainly too wide.

To insert a breakpoint at 600px, create two new style sheets, one to use when the browser is 600px and below, and one for when it is wider than 600px.


Finally, refactor the CSS. In this example, we"ve placed the common styles such as fonts, icons, basic positioning, and colors in weather.css . Specific layouts for the small screen are then placed in weather-small.css , and large screen styles are placed in weather-large.css .

Pick minor breakpoints when necessary

In addition to choosing major breakpoints when layout changes significantly, it is also helpful to adjust for minor changes. For example, between major breakpoints it may be helpful to adjust the margins or padding on an element, or increase the font size to make it feel more natural in the layout.

Let"s start by optimizing the small screen layout. In this case, let"s boost the font when the viewport width is greater than 360px. Second, when there is enough space, we can separate the high and low temperatures so that they"re on the same line instead of on top of each other. And let"s also make the weather icons a bit larger.

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.

Narrow screen devices (e.g. mobiles) 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 many pages are not mobile optimized, 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.

Enter viewport meta tag

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.

To mitigate this problem, Apple introduced the "viewport meta tag" in Safari iOS to let web developers control the viewport"s size and scale. Many other mobile browsers now support this tag, although it is not part of any web standard. Apple"s documentation does a good job explaining how web developers can use this tag, but we had to do some detective work to figure out exactly how to implement it in Fennec. For example, Safari"s documentation says the content is a "comma-delimited list," but existing browsers and web pages use any mix of commas, semicolons, and spaces as separators.

Learn more about viewports in different mobile browsers in A Tale of Two Viewports at quirksmode.org.

Viewport basics

A typical mobile-optimized site contains something like the following:

The width property 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 the width of the screen in CSS pixels at a scale of 100%. (There are corresponding height and device-height values, which may be useful for pages with elements that change size or position based on the viewport height.)

The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale , minimum-scale , and user-scalable properties control how users are allowed to zoom the page in or out.

A pixel is not a pixel

In recent years, screen resolutions have risen to the size that individual pixels are hard to distinguish with the human eye. For example, recent smartphones generally have a 5-inch screens with resolutions upwards of 1920-1080 pixels (~400 dpi). 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 web sites. Peter-Paul Koch wrote about this problem in A pixel is not a pixel .

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 will probably 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. This is consistent with the CSS 2.1 specification , which says:

If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values. It is recommended that the pixel unit refer to the whole number of device pixels that best approximates the reference pixel. It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm"s length.

For web developers, this means that the size of a page is much smaller than the actual pixel count and browsers may size their layouts and images accordingly. But remember that not all mobile devices are the same width; you should make sure that your pages work well in a large variation of screen sizes and orientations.

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 doesn"t render 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 like the iPad. (Allen Pike"s Choosing a viewport for iPad sites has a good explanation for web developers.)

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

Not all mobile browsers handle orientation changes in the same way. For example, Mobile Safari often just zooms the page when changing from portrait to landscape, instead of laying out the page as it would if originally loaded in landscape. If web developers want their scale settings to remain consistent when switching orientations on the iPhone, they must add a maximum-scale value to prevent this zooming, which has the sometimes-unwanted side effect of preventing users from zooming in:

Suppress the small zoom applied by many smartphones by setting the initial scale and minimum-scale values to 0.86. The result is horizontal scroll is suppressed in any orientation and the user can zoom in if they want to.

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

Specification Status Comment
CSS Device Adaptation
The definition of "" in that specification.
Working Draft Non-normatively describes the Viewport META element

There is clearly demand for the viewport meta tag, since it is supported by most popular mobile browsers and used by thousands of web sites. It would be good to have a true standard for web pages to control viewport properties. As the standardization process proceeds, we at Mozilla will work to keep up to date with any changes.