Determining the width of a webpage in inches

css, html, javascript, responsive-design

Solution

It's a non-trivial problem.

Here's a link to a site that has a function (`getUnits`) to get the current computed style in a measurement unit of your choice (including inches) https://web.archive.org/web/20120427144951/http://upshots.org:80/javascript/javascript-get-current-style-as-any-unit

Using this function, you could check `if (getUnits(document.body, "width").inch < 4)`. The way this function works, for the curious, is by creating a temporary element in the desired measurement space and reading off the ratio to pixels. In this way you let the browser respond based on its own knowledge the device's PPI. So this is sort of a polyfill for `window.devicePixelRatio`, however browsers mostly lie about their PPI. For these purposes, though, it doesn't matter since they will be applying the same lie to your inch-unit CSS.

Problem

I have a CSS stylesheet that uses media queries to change how a page is displayed based on how many inches it is in width (for instance, if it is smaller than 4 inches or being displayed on a handheld device, it assumes a more mobile-friendly LAF). The problem I have is with its content. On the homepage, there is a dock-style interface that dynamically changes height based on the current height and width of the window so that the text and items never leave the screen. However, my JS that determines this size does not know when the stylesheet has changed for handheld devices or small screens, so the behavior continues unpredictably in this mode. How can I use JavaScript detect when the page is less than or equal to 4 inches so that I can disable the auto-resizing of the then-reformed dock?

Original source