问题
It seems that Firefox and Webkit browsers measure different things when using a max-width media query. While investigating breakpoints for a responsive design overhaul, I found that Chrome will include stylesheets at the expected width, but Firefox always included the sheet at a narrower than expected width. For example:
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" media="screen and (max-width: 480px)" href="/480.css" />
I would expect the width of the document when resizing the window from 1280 to 480 pixels wide would trigger the inclusion of the stylesheet at a document width of 480. But Firefox does not include it until a width of 463px.
I ran some tests and see that in Chrome, the width seems to be based off of window.innerWidth, while Firefox is using document.documentElement.clientWidth. This information is confirmed by the use of the an event listener on window.matchMedia("(max-width: 480px)"). (Screen shot).
My question is: am I the only one noticing this? I can't find any other reference to this behavior, so maybe I'm doing something wrong?
回答1:
A bit too late maybe, but I'm facing the same issue. Yet, here's some insight from 456 Berea
The ‘width’ media feature describes the width of the targeted display area of the output device. For continuous media, this is the width of the viewport (as described by CSS2, section 9.1.1 [CSS21]) including the size of a rendered scroll bar (if any).
The width should include the vertical scrollbar. Safari does not. Arguably the WebKit behaviour is better for web developers in a sense, since scrollbar width is not exactly the same across browsers and platforms.
Either way, just a heads up that browser behaviour is inconsistent on this point. In many cases it doesn’t matter a whole lot, but it can be annoying if you want pixel-precision control of when layout changes occur.
回答2:
According to documentation for clientWidth it could be related to the DOCTYPE.
Note that the clientWidth property is special for the html element. It returns the width of the browser's client area without the vertical scrollbar for any doctype. If no doctype is specified, the clientWidth property of the html element contains different values in the browsers.
Here's another link I found helpful for a few browser related cases regarding browser widths.
来源:https://stackoverflow.com/questions/8977605/firefox-versus-webkit-measurements-for-media-queries-based-on-width