snippetjavascriptCritical
How to get the browser viewport dimensions?
Viewed 0 times
browserhowviewportdimensionstheget
Problem
I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?
Or better yet, the viewport size of the browser with JavaScript? See green area here:
Or better yet, the viewport size of the browser with JavaScript? See green area here:
Solution
Cross-browser
Resources
@media (width) and @media (height) values let vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
let vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
window.innerWidth and window.innerHeight- gets CSS viewport
@media (width)and@media (height)which include scrollbars
initial-scaleand zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the@mediavalues
- zoom may cause values to be 1px off due to native rounding
undefinedin IE8-
document.documentElement.clientWidth and .clientHeight- equals CSS viewport width minus scrollbar width
- matches
@media (width)and@media (height)when there is no scrollbar
- same as
jQuery(window).width()which jQuery calls the browser viewport
- available cross-browser
- inaccurate if doctype is missing
Resources
- Live outputs for various dimensions
- verge uses cross-browser viewport techniques
- actual uses
matchMediato obtain precise dimensions in any unit
Context
Stack Overflow Q#1248081, score: 1729
Revisions (0)
No revisions yet.