Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the browser viewport dimensions?

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:

like image 560
Alix Axel Avatar asked Aug 08 '09 05:08

Alix Axel


People also ask

How do I check my viewport size in Chrome?

It includes, among other things, a responsive design mode from the Tools menu (see screenshot). And from the Web Developer Toolbar, click on Resize tab and select Display Window Size (see screenshot) which shows window and more importantly viewport size.

What is the size of the viewport?

A viewport is defined by the size of the rectangle filled by a web page on your screen. The viewport is the size of the browser window, minus the scroll bars and toolbars. Browsers use “CSS pixels.” For many devices, such as those with retina screens, the viewport is smaller than the advertised device resolution.

How do I get the height of a viewport in CSS?

It is not possible to get the height of the screen from CSS. However, using since CSS3 you can use media queries to control the display of the template as per the resolution. If you want to code on the basis of height using media queries, you can define style-sheet and call it like this.


1 Answers

Cross-browser @media (width) and @media (height) values 

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) const 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-scale and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the @media values
  • zoom may cause values to be 1px off due to native rounding
  • undefined in 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 matchMedia to obtain precise dimensions in any unit
like image 197
ryanve Avatar answered Sep 29 '22 16:09

ryanve