The tricky bits
However, there are two tricky bits: the device-width media query and the ≶meta name=”viewport” width=”device-width” >tag. Both work with device pixels, and not with CSS pixels, because they report on the context of the web page, and not on its inner CSS workings.
device-width媒体查询和≶ meta name=”viewport” width=”device-width” >都是指设备像素,而不是css像素。
The media query
The device-width media query measures the width of the device in device pixels. The width media query measures the total width of the page in CSS pixels, which, for reasons I’ll explain later, is at least 980px on the iPhone.
The device-width media query works as follows:1
2
3
4
5
6
7
8
9
10
11div.sidebar {
width: 300px;
}
@media all and (max-device-width: 320px) {
// styles assigned when device width is smaller than 320px;
div.sidebar {
width: 100px;
}
}
Now the sidebar is 300 CSS pixels wide, except when the device width is 320 device pixels or less, in which case it becomes 100 CSS pixels wide.
侧边栏为300 css像素宽,除非设备的宽度小于等于320,此时,侧边栏的css像素变为100px.
By the way, in theory you could use a media query that queries the device screen in centimeters or inches (@media all and (max-device-width: 9cm)). Unfortunately it seems badly to outright unsupported, even by the iPhone. The problem here is that physical units such as inches are usually translated to (CSS) pixels; thus width: 1in equals 96 pixels on all browsers I tested so far (and that’s quite a few). So these media queries are unreliable.
理论上说可以使用设备屏幕的厘米或者英寸来媒体查询。但是基本浏览器都不支持。
The tag
In general <meta name=”viewport” content=”width=device-width” > is even more useful. This tag, originally Apple-proprietary but meanwhile supported by many more mobile browsers, actually makes the layout viewport fit the device exactly.
Now what is the layout viewport? It’s the area (in CSS pixels) that the browser uses to calculate the dimensions of elements with percentual width, such as div.sidebar {width: 20%}. It’s usually quite a bit larger than the device screen: 980px on the iPhone, 850px on Opera, 800 on Android, etc.
If you add <meta name=”viewport” content=”width=device-width” >, the width of this layout viewport is constrained to the device width in device pixels; 320 of them in the iPhone’s case.
So basically Google has already inserted a layer of what are apparently called dips; device-independent pixels. This layer comes between the official, reported screen size and the CSS pixels web developers work with.