Note

A tale of two viewports - part one

https://www.quirksmode.org/mobile/viewports.html

Device pixels and CSS pixels

Device pixels are the kind of pixels we intuitively assume to be “right.” These pixels give the formal resolution of whichever device you’re working on, and can (in general) be read out from screen.width/height. 设备像素就是我们直觉上的像素。这些像素为你使用的设备上提供的正规的分辨率,其值能够从screen.width/height读取。

Zooming as implemented in modern browsers consists of nothing more than “stretching up” pixels. 现代浏览器实现缩放的方式都是“拉伸像素”。例如:当一个width为128px的元素被放大200%时,形式上,该元素的width仍然为128个CSS像素,但是它占据了256个设备像素。

Four pixels on 100% zoom level: CSS pixels fully overlap with device pixels

100%-zoom-level

Zoom out: The CSS pixels start to shrink, meaning that one device pixel now overlaps several CSS pixels.

zoom-in

Zoom in: the opposite happens. The CSS pixels start to grow, and now one CSS pixels overlaps several device pixels 100% zoom: At zoom level 100% one CSS pixel is exactly equal to one device pixel.

zoom-out

Screen size

screen.width/height:

screen-size

Window size

window.innerWidth/Height:

window-size

Scrolling offset

window.pageX/YOffset:

window-size

Concept: the viewport

The function of the viewport is to constrain the <html> element, which is the uppermost containing block of your site.

In theory, the width of the <html> element is restricted by the width of the viewport. The <html> element takes 100% of the width of that viewport. 理论上,<html>元素的宽度被viewport所限定。

The viewport, in turn, is exactly equal to the browser window: it’s been defined as such. The viewport is not an HTML construct, so you cannot influence it by CSS. It just has the width and height of the browser window — on desktop. On mobile it’s quite a bit more complicated. viewport,接着,实际上等于浏览器窗口:它就是那么定义的。viewport不是一个HTML结构,所以你不能用CSS来改变它。它在桌面环境下只是拥有浏览器窗口的宽度和高度。在移动环境下它会有一些复杂。

Measuring the viewport

document.documentElement.clientWidth/Height:

window-size

Measuring the <html> element

document.documentElement.offsetWidth/Height:

window-size

Event coordinates

window-size window-size window-size

Media queries

There are two relevant media queries: width/height and device-width/device-height:

  1. width/height uses the same values as documentElement.clientWidth/Height (the viewport, in other words). It works with CSS pixels.

  2. device-width/device-height uses the same values as screen.width/height (the screen, in other words). It works with device pixels.

window-size

viewport html css