Explain Codes LogoExplain Codes Logo

How to get the browser viewport dimensions?

javascript
responsive-design
browser-quirks
viewport-dimensions
Nikita BarsukovbyNikita Barsukov·Sep 15, 2024
TLDR

Use window.innerWidth and window.innerHeight to obtain the viewport width and height.

const width = window.innerWidth, height = window.innerHeight; console.log(`Viewport: ${width} x ${height}`); // Prints viewport dimensions like a boss!

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.
const width = document.compatMode === "CSS1Compat" ? document.documentElement.clientWidth : document.body.clientWidth; // Because browser quirks don't take days off const height = document.compatMode === "CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight; // 'Cause we roll with the punches

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:

window.addEventListener('resize', function() { const newWidth = window.innerWidth; const newHeight = window.innerHeight; // Time to work that adaptive magic! });

This ensures your design is always up-to-date with the user's viewport.