Skip to main content

Setting The Viewport

The viewport is the visible area of a web page that the user can see.

The viewport size depends on the device. It will be much smaller on a mobile phone than on a computer screen.

You should add the following <meta> element in the <head> section of all your web pages:

This tells the browser how to control the page's size and scaling.

The width=device-width part sets the page width to match the screen width of the device, which changes depending on the device.

The initial-scale=1.0 part sets the starting zoom level when the page first loads in the browser.

Viewport meta tag

Add this <meta> tag inside the <head> of your HTML page to set the viewport.

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

Size Content to The Viewport

Users are used to scrolling web pages up and down on both desktop and mobile devices, but not side to side.

If a user has to scroll horizontally or zoom out to see the full page, it creates a bad experience.

Here are some rules to follow:

  • Do not use large fixed-width elements. For example, if an image is wider than the viewport, it will cause horizontal scrolling. Always adjust content to fit within the viewport width.
  • Do not let content depend on a specific viewport width to look good. Screen sizes vary a lot between devices, so your content should work at any width.
  • Use CSS media queries to apply different styles for small and large screens. Avoid setting large absolute widths on page elements. Use relative values like width: 100% instead. Also be careful with large absolute positioning values, as they may push elements outside the viewport on small screens.