CSS - Viewport (Reader's window)

About

The viewport 1) is the viewing area on a screen media.

It's then a property of media.

When the viewport is smaller than the area of the canvas on which the document is rendered, the user agent (browser) should offer a scrolling mechanism.

There is at most one viewport per canvas, but user agents may render to more than one canvas (i.e., provide different views of the same document).

The layout viewport is the area in CSS pixels that the browser uses to calculate the dimensions of elements below the root element with percentage width.

Management

Definition

In a HTML page, you can define the viewport via the meta tag named viewport

A typical mobile-optimized site will contain this viewport definition. (ie the viewport will be set exactly to the the device width)

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

where:

  • width is the size of the viewport defined by:
  • initial-scale 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.

Calculation

  • This is window calculation, not the viewport but it can help (ie if you have element positioned absolutely outside, the innerwidth will be greater than the viewport. The outside Width takes the whole window browser width
console.log(window.innerWidth)

Programmatic

Query

  • Create a media query object (known as a media query list)
let maxWidthMediaQuery = window.matchMedia('(max-width:750px)');
  • Create a function
function viewPortReporter(mediaQueryObject){
    if (mediaQueryObject.matches) {
        console.log('Smaller than 750px');
    } else {
        console.log('Bigger than 750px');
    }
}
  • Does the media match the query ?
viewPortReporter(maxWidthMediaQuery);

Listener

You can listen to viewport changes with a change event listener.

This listener is also known as a media listener.

maxWidthMediaQuery.addEventListener("change",viewPortReporter);
// deprecated, old
// maxWidthMediaQuery.addListener(viewPortReporter);

Example: Just minimize and maximize your browser windows below 750px and you should see two messages.


Powered by ComboStrap