How to get the browser viewport dimensions?
Use window.innerWidth
and window.innerHeight
to obtain the viewport width and height.
Getting deeper into dimensions
Browser quirks and standards mode
Each browser comes with its own set of idiosyncrasies (aka quirks). To get the accurate viewport size, we'll have to bend to their ways:
- Standards mode: Use
document.documentElement.clientWidth
and.clientHeight
. - Quirks mode: Use
document.body.clientWidth
and.clientHeight
.
Mobile scaling
Mobile browsers sometimes think they're smarter than us. They scale down viewport dimensions depending on zoom level and initial-scale
settings. Keep that in mind when debugging on mobile, it's not you, it's them!
Pixel-perfect precision
Due to how browsers handle pixel rounding, there's a chance you might encounter 1px discrepancies. It’s not a bug, it's a feature!
Extra goodies for ultimate precision
Certain libraries can give you extra control where native JavaScript may not:
- Verge: Handles all the back-stage chaos for consistent, cross-browser viewport techniques.
- Actual: Uses
matchMedia
for precise dimensions in various units.
If you swear by jQuery, use $(window).width()
and $(window).height()
, and let jQuery deal with browser differences.
Responsiveness – embrace change
Being responsive means changing with changing viewport dimensions. Add an event listener to resize your content as the viewport resizes:
This ensures your design is always up-to-date with the user's viewport.
Was this article helpful?