← Concepts

阅读中文版本

Visual Viewport

The visual viewport is the on-screen window onto the layout viewport — what pinch zoom, keyboards, and browser chrome actually resize — distinct from the layout viewport media queries see.

browser

Definition

The visual viewport represents the currently visible portion of the page, affected by pinch zoom, dynamic toolbars, and on-screen keyboards. The layout viewport is the stable CSS reference that media queries and vw units resolve against. Scale, offset, and resize events on the visual viewport expose mobile interactions desktop code often ignores.

Context and scope

Critical for mobile keyboards overlaying inputs, sticky toolbars under pinch zoom, bottom sheets positioned above the keyboard, and correctly responding to browser chrome show and hide.

Common misconceptions

  • window.innerWidth tracks the layout viewport — it reflects the visual viewport and changes with zoom and chrome on mobile
  • Position: fixed pins to the screen — fixed elements anchor to the layout viewport, so they move under the visual viewport when zoomed
  • The keyboard resizes the page — on many platforms the keyboard overlays without resizing, so layout media queries never fire

Anti-patterns

  • Using layout-viewport units to position chat inputs and losing them behind the on-screen keyboard
  • Listening only to window resize and missing visual viewport offset changes from pinch zoom and toolbars
  • Fighting zoom with maximum-scale and shipping a worse accessibility experience instead of designing for zoom

Related concepts

Related examples

Authoritative source

https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport

What it is

The page layout computes against the layout viewport, while the user actually sees the visual viewport sliding over it: zoomed, offset, partially covered by the keyboard or toolbar. The two diverge precisely in the interactions that define mobile UX.

How it works

window.visualViewport exposes scale, offsetLeft and offsetTop, width and height, plus resize and scroll events. The interactive-widget meta setting influences whether the keyboard resizes or overlays the visual viewport. Fixed elements belong to the layout viewport, so they slide out from under zoom.

When to care

Chat apps keeping the composer above the keyboard, maps keeping controls in view under zoom, and full-screen experiences syncing to toolbar state. Prefer listening to visualViewport over window resize on mobile, with desktop fallbacks.

Pitfalls

Keyboard behavior varies across engines and the interactive-widget values: some resize the layout viewport, some only overlay. Fractional scale values make px math drift; round through getBoundingClientRect for hit testing. Hybrid apps add their own chrome that no web API reports.