Использование метатега viewport для управления разметкой на мобильных браузерах. Использование метатега viewport для управления разметкой на мобильных браузерах Значение метатега 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.

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.


Я уверен, что многие используют мета-тег Viewport для масштабирования дизайна, но знаете ли вы, что этот тег также может быть очень полезен для мобильных устройств? Если у вас нет времени, чтобы преобразовать ваш проект, тем не менее, вам следует прочитать эту статью о том, как использовать тег Viewport для улучшения внешнего вида вашего проекта на мобильных устройствах.

Главное использование тега Viewport

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

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

Использование тега Viewport для сайтов, не рассчитанных под мобильные устройства.

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

Пример


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

< meta name = "viewport" content = "width=1024" >

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

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

Вы можете просто исправить это, установив ширину окна в 720px. Ширина вашего дизайна не меняется, но iPhone будет масштабировать, чтобы поместиться в 720px.

< meta name = "viewport" content = "width=720" >

Распространенная ошибка

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

Для настройки окна браузера можно использовать специальный тег HTML следующего вида: . Однако следует учесть, что в официальный стандарт W3C он не включён — его впервые ввела в iPhone компания Apple. А вслед за ней и остальные компании — поставщики браузеров. Мета-тег сегодня активно используется, благодаря возросшей популярности Android, iOS и остальных платформ, на которых работают смартфоны и планшеты.

Исключительное предназначение «Meta name viewport» — для настройки разметки страницы. Поэтому его можно отнести к CSS, чего и хотят добиться в стандарте W3C. В статье мы рассмотрим использование мета-тега Viewport в html.

Viewport

Проведём небольшой эксперимент — сделаем элементарную html-страницу со следующей разметкой:

Welcome, USER!

Welcome, USER!

Сохраним её и откроем в смартфоне:

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

Hello world!

Hello world!

Текст хорошо читается, страница отображается корректно. Почему так?

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

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

Уменьшение масштаба и частичное отображение несёт в себе определённый смысл. Так как мобильный браузер, видя страницу, определяет, что она предназначена для стационарного ПК. Это «определение» верно для значительного числа интернет-сайтов. Далее, он устанавливает ширину в 980 пикселей (указано для Safari) для всей интернет-страницы и начинает максимально уменьшать масштаб, чтобы наилучшим образом показать её на экране. Открывая такие сайты мы видим их полностью умещёнными по ширине в экран, но в несколько раз меньше своих реальных размеров.

Используя мета-тег Вивпорт, мы оптимизируем страницы для смартфонов и задаём правила, благодаря которым область просмотра «будет вести себя правильно». В рассмотренном примере, значение «device-with» указывает браузеру устройства, что область просмотра имеет такую же ширину, что и ширина самого устройства. Если эта ширина экрана устройства равна 300 пикселей, то можно указать width=300px, но смартфоны разные и использовать «device-with» оптимальней.

Примеры

Можно указать начальный масштаб страницы и её запретить масштабирование. Рассмотрим пару вариантов:

Здесь мы имеем указание — ширина страницы равна ширине устройства (width=device-width), начальный масштаб (initial-scale=1.0), максимальный масштаб (maximum-scale=1.0) и запрет для пользователя на изменение масштаба (user-scalable=no).

Это более простой и распространённый вариант.

Использовать первый вариант нужно использовать с особой осторожностью. Так как запрет для пользователя на увеличение или уменьшение масштаба может привести к плохой читабельности текстового содержимого. И как следствие — увеличению показателя отказов.

Устаревшие модели смартфонов не поддерживают относительно новый мета-тег Вивпорт. Для них есть:

и другие.

Параметры Viewport

  • Определение ширины — «width». Можно указывать целое положительное значение от 200 до 10 тысяч пикселей. Или использовать постоянное специальную константу, которую мы уже рассмотрели «device-width». Если константа или значение не будет указано, то будет использовано значение по-умолчанию: для Opera — 850, для Safari — 980, для Android Webkit — 800, а для IE — 974 пикселя.
  • Определение высоты «height». Можно задавать значение от 223 до 10 000 пикселей, или указать константу «deviceheight», но лучше вообще игнорировать.
  • Определение начального масштаба страницы «initial-scale». Используется целое число от 0,1 до 10. Если указано 1.0 — масштабирование производиться не будет. Если 2 — увеличение в 2 раза.
  • Разрешение пользователю на изменение масштаба «user-scalable». Принимает только два значения — да («yes») или нет («no»), последнее — запрет на изменение.
  • Минимальный и максимальный масштабы «minimum-scale» и «maximum-scale». Указывается в виде чисел от 0,1 до 10. Если 1.0 — масштабирование запрещено.

Когда мы хотим настроить окно браузера на нашем устройстве, мы, как правило, используем HTML тег . Однако, как ни странно, мета-тег не является «нормативным» — его нет в официальном стандарте W3C.

Мета-тег viewport был впервые внедрён компанией Apple в iPhone, а затем и другими поставщиками браузеров. Сегодня он широко используется благодаря популярности iOS, Android и других платформ для планшетов и смартфонов.

Так как мета-тег viewport предназначен исключительно для настройки разметки, можно сказать, что он по праву относится к CSS. Именно поэтому W3C стремится стандартизировать новый метод адаптации, при котором управление окном переносится из HTML в CSS.

CSS правило @viewport

С новым правилом @viewport мы имеем то же самое управление окном, что и с мета-тегом, за исключением того, что такое управление осуществляется исключительно через CSS. Также как и при использовании мета-тега, рекомендуется устанавливать ширину окна браузера, используя не зависимую от устройства device-width:

@viewport {
width: device-width;
}

На сегодняшний день @viewport используется программистами для “snap mode” в IE10 - функция Windows 8, позволяющая работать в мультиоконном режиме. Как ни странно, IE10 игнорирует мета-тег, если размер окна менее 400 пикселей, что приводит к невозможности оптимизации сайтов, использующих этот мета-тег, к таким маленьким окнам. Чтобы это исправить, программисты должны использовать упомянутый выше параметр device-width, или определить правило @viewport в медиа-запросе.

Использование @viewport в медиа-запросах

Мы можем использовать @viewport в медиа-запросах. Например, следующий медиа-запрос используется для настройки разметки окна шириной менее 400 пикселей (например, мультиоконный режим в IE10) на ширину 320 пикселей.

@media screen and (max-width: 400px) {
@-ms-viewport { width: 320px; }
...
}

В данном примере, если устройство настроено на диапазон разрешения от 640 до 1024 пикселей, правило @viewport масштабирует окно до 640 пикселей.

@media screen and (min-width: 640px) and (max-width: 1024px) {
@viewport { width: 640px; }
...
}

Новые дескрипторы @viewport

Несмотря на то, что мы можем управлять функцией увеличения и масштабирования, некоторые свойства viewport - или как их сейчас называют «дескрипторы» - всё же изменились.

zoom

Дескриптор zoom - это эквивалент initial-scale в мета-теге. Также как и minimum-scale и maximum-scale, существуют дескрипторы для max-zoom и min-zoom:

@viewport {
width: device-width;
zoom: 2;
}

user-zoom

Дескриптор user-zoom эквивалентен параметра user-scalable

@viewport {
width: device-width;
user-zoom: fixed;
}

Поддержка браузерамиами

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

Пока что к правилу @viewport необходимо добавлять вендорный префикс:

@-ms-viewport {
width: device-width;
}
@-o-viewport {
width: device-width;
}
@viewport {
width: device-width;
}

Конечно же, нам до сих пор необходимо включать мета-тег viewport в html страницу, т.к. в ближайшее время он никуда не денется. Но уже не так страшно смотреть в будущее - добавление правила @viewport всего лишь делает наши сайты и приложения готовыми к переменам

Общая ошибка

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

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.