Curriculum
Course: CSS Responsive
Login
Text lesson

What is The Viewport?

The viewport size differs depending on the device, typically smaller on mobile phones compared to computer screens.

In the past, web pages were primarily designed for computer screens with static layouts and fixed sizes. However, with the emergence of tablets and mobile phones, these fixed-size web pages became too large to fit within the viewport. As a result, browsers on these devices resorted to scaling down the entire web page to accommodate the screen size.

While this approach provided a quick fix, it was not without its flaws.

Setting The Viewport

HTML5 introduced a technique for web designers to manage the viewport using the <meta> tag.

It is recommended to incorporate the following <meta> viewport element into all your web pages:

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

This provides instructions to the browser regarding how to manage the dimensions and scaling of the page.

The “width=device-width” segment establishes the page width to adapt to the screen width of the device, which may vary depending on the device.

The “initial-scale=1.0” segment sets the initial zoom level when the page is initially loaded by the browser.

Below is an example of a web page without the viewport meta tag, and then the same web page with the viewport meta tag:

Image

Note: If you are accessing this page using a smartphone or tablet, you can tap on the two links provided above to observe the contrast.

Size Content to The Viewport

Users are accustomed to vertical scrolling on both desktop and mobile devices, but horizontal scrolling or zooming out to view the entire web page can lead to a subpar user experience.

Here are some additional guidelines to adhere to:

  1. Avoid using large fixed-width elements – For instance, displaying an image wider than the viewport can trigger horizontal scrolling. Ensure that such content fits within the viewport width.
  2. Do not rely on a specific viewport width for optimal rendering – Given the variability of screen dimensions and CSS pixel widths across devices, content should not depend on a particular viewport width to display correctly.
  3. Utilize CSS media queries to tailor styling for different screen sizes – Employ relative width values like width: 100% instead of large absolute CSS widths for page elements, which might exceed the viewport width on smaller devices. Additionally, exercise caution when using large absolute positioning values to prevent elements from extending beyond the viewport on small devices.