Media queries with rem units in Chrome?

2019-02-14 09:45发布

问题:

Is it possible to use rem units in Chrome media queries?

rem units work flawlessly in Chrome, it just seems that they are not supported in media queries. Is this possible? Or is there something else wrong with this CSS?

body { background-color: yellow; }

@media only all and (max-width: 40rem) {
    body { background-color: red; }
}

@media only all and (min-width: 40rem) and (max-width: 60rem) {
    body {background-color: green;}
}

@media only all and (min-width: 60rem) {
    body { background-color: blue; }
}

Live at http://jsfiddle.net/jsQ2N/2/show/, em-only version at http://jsfiddle.net/jsQ2N/3/show/.

回答1:

The spec says this about relative units such as both rem and em:

Relative units in media queries are based on the initial value, which means that units are never based on results of declarations. For example, in HTML, the ‘em’ unit is relative to the initial value of ‘font-size’.

(The initial value of font-size is medium, which is usually equal to the default font size setting in the browser's user preferences.)

Since Media Queries 3 doesn't define special rules for any specific units besides the above quote on relative units, rem should act like em, working off the initial value of font-size. If it doesn't work in Chrome, it's most likely a bug.



回答2:

It turns out that this is Webkit issue #78295 (unresolved as of 2012-08): Support for CSS rem unit in Media Queries (via http://fvsch.com/code/bugs/rem-mediaquery/).



回答3:

After posting the answer below this question bugged me. I did a little more testing in Chrome with the site I'm working on. The post about rem's being a bug in Chrome is correct, they don't work, so I'm changing to pixels just for the media queries.

*To answer your question, rems are working for me to adjust the height of a content area using media queries. It's how Chrome interperets browser width that seems to differ from Firefox, but that's not a rem based problem.

Keep in mind, when I use rems and ems it is after setting font-size: 1em; or font-size: 16px; for html or body. I'm leaning towards sticking to font-size: 1em; on the html tag. That creates a default that works from whatever the user has set for a default font size, on whatever device they're using. Rem's are relative to the root value of 1em. That root value is given by the user's default font-size, so everything should scale according to the user's font size preference and be device/pixel-density independent.

This means whether the user is using a "normal" 72 or 96 pixel/inch device, or a Retina (or other high pixel density screen) everything should look "relatively" the same from device to device.