What is a viewport?

What is a viewport?

and how it affects the CSS and @media rules?

In computer graphics, a viewport is a polygonal or rectangular area that a person sees at a time.

In web browser language, it refers to the portion of the page that is currently visible in its window excluding the UI. It varies with the devices and will be smaller on a mobile phone screen than on a computer screen. The content outside the viewport is not visible until scrolled or shifted down into view.

There are two types of viewports:

  1. Layout viewport.

    It is the area into which the browser renders a web page. Basically, it represents the whole page.

    It remains constant throughout after the page is rendered.

  2. Visual viewport.

    It is the portion of the web page that is currently visible in the browser and is subject to change. It does not include on-screen keyboards, places outside of a pinch-zoom area, or any other feature that does not scale with the page size.

When a user pinch-zooms a page, opens a dynamic keyboard, or reveals a previously concealed address bar, the visual viewport shrinks but the layout viewport remains unaltered.

Sticky headers and footers cling to the top and bottom of the layout viewport and hence remain visible when we zoom in.

Scrolling down changes the contents of the visual viewport and brings the bottom of the layout viewport into view, displaying the sticky footer, which will then remain at the bottom. So we can say that any sub-viewport that is fully or partially displayed within the layout viewport is a visual viewport.

It is essential to know about the viewport since width and height media queries are relative to the viewport, not the browser window. So when the device changes, the viewport changes the @media rules work differently.

The @media rule applies styling selectively based on the width of the user’s viewport and using @media rules enables us to target the user’s viewport, as it allows us to ensure that the styling of the page is dynamic and responsive.

If you want to learn more about viewport, you can look at this site.