What is a viewport?
A viewport meta tag defines how a web page is rendered and displayed on mobile devices. It improves the presentation of the page’s content on the mobile browser’s and makes for a richer interaction and user experience.
If the viewport is not defined, the mobile device will display the web page as it has been designed for the desktop, while fitting to the screen of the mobile, without any scaling of the page’s dimensions.
A viewport meta tag thus gives control over the dimensions of a page and how it will scale and fit on various mobile devices.
The image on the left shows what the webpage looks like without a configured viewport when viewed on a mobile device. The image on the right, on the other hand, displays the web page as defined by the viewport for a particular device.
Why is Configuring View Port Important?
If the viewport is not defined, mobile devices will render the page at a width between 800 to 1024 CSS pixels. The page is adjusted in a way that it fits on the mobile’s display. So in order to properly view or interact with the page, the user is forced to zoom in.
By using the meta viewport tag, you give the mobile browser directions on how to render the page and in what dimensions.
How to configure the viewport
To configure the viewport, add the following code in the header section of the document
<meta name=viewport content="width=device-width, initial-scale=1">
There are two kinds of viewports:
- Fixed-width viewport – A specific size can be set for the viewport. For instance, the width can be defined as width= 1024 While not recommended, the fixed-width viewport can be used to ensure that web pages that have a fixed width, are displayed properly
- Responsive viewport – When the value width=device-width is used, it directs the web page to scale itself according to the mobile device’s screen size. It thus allows the page to reflow the content according to different screen sizes.