- A complete guide to get viewport, device and document sizes with JavaScript
- Viewport size
- 1. innerWidth and innerHeight properties
- 2. outerWidth and outerHeight properties
- Device size
- Document size
- 1. clientWidth and clientSize properties
- 2. offsetWidth and offsetHeight properties
- 3. scrollWidth and scrollHeight properties
- Final thoughts
- Как получить размеры экрана, окна и веб-страницы в JavaScript?
- 1. Экран
- 2. Окно
- 3. Размер веб-страницы
- 4. Заключение
- Window screen.width
- Note
- Syntax
- Return Value
- More Examples
- Browser Support
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
A complete guide to get viewport, device and document sizes with JavaScript
JavaScript provides a native API to get the width and height of a viewport. But it’s important to understand the difference between what sizes you are getting as it may cause you some trouble.
When making calculations you have to distinguish between viewport, device, and document. Because at times the values of all three may be the same. However they may sound and look as if they are the same, but really these are three different concepts.
Viewport size
In web development terms the viewport is treated the same as the browser window, including the rendered scrollbar if any.
MDN distinct two types of viewports:
- Layout viewport — the area which is available to be seen;
- Visual viewport — the portion of the viewport that is currently visible (e.g. zoomed area on a mobile device).
When we’re talking about the viewport for the most part we’re talking about the Layout viewport. There are 2 ways to get the width and height of the viewport (Layout viewport):
1. innerWidth and innerHeight properties
The innerWidth property returns the interior width of the window in pixels (including the width of the scroll bar, if one is present).
const viewportWidth = window.innerWidth
The innerHeight property returns the interior height of the window in pixels (including the height of the scroll bar, if one is present).
const viewportHeight = window.innerHeight
Both properties return the integer value and are read-only.
Browser Support: innerWidth and innerHeight supported by all browsers.
2. outerWidth and outerHeight properties
The outerWidth read-only property returns the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.
const browserWidth = window.outerWidth
The outerHeight read-only property returns the height in pixels of the whole browser window, including any sidebar, window chrome, and window-resizing borders/handles.
const browserHeight = window.outerHeight
Both properties return the integer value and are read-only.
Browser Support: outerWidth and outerHeight supported by all browsers.
Device size
The device size is often referred to as a screen or display size. This is the size of an actual area of the device where users see the content. Unlike viewport or document size the values of the screen (display) remain unaltered.
To get the size of the screen the window.screen property can be used. It is a part of the Screen API. The screen property returns an object that contains data about the current screen.
Some of the properties of the screen object can be utilized to get the size of the screen.
screen.width property returns a screen width in pixels. The returned value is an integer and read-only.
const screenWidth = window.screen.width
screen.height property returns a screen height in pixels. The returned value is an integer and read-only.
const screenHeight = window.screen.height
Browser support: Screen API supported in all browsers.
Document size
The following ways will get the size of the document. Now the difference from the viewport is that the document can be larger than the viewport itself. Also, other things need to be considered. But let’s move step by step.
To get the size of the document you need to get the html element that represents the document. The document.documentElement property returns the root element of the current document, that is html .
1. clientWidth and clientSize properties
While the clientWidth property returns the inner width of an element in pixels. Initially, it includes paddings but excludes borders, margins, and scrollbars. But for html element it’s a special case and the viewport width is returned (in pixels), excluding scrollbar width.
const documentWidth = document.documentElement.clientWidth
The clientHeight property returns the inner height of an element. Just like with the clientWidth , the clientHeight is a special case when used on the html element. And it returns the viewport height (in pixels), excluding scrollbar height.
const documentHeight = document.documentElement.clientHeight
When using these properties the scrollbar width and height are excluded — this is another thing to consider I mentioned before.
Note: even if the html element has the CSS width or height rules applied, the clientWidth and clientHeight properties will always return viewport width and height (without scrollbars).
Browser Support: clientWidth and clientHeight supported by all browsers.
2. offsetWidth and offsetHeight properties
The HTMLElement.offsetWidth property can be used on an html element to determine the width of the document. Note: that the document width can be larger than the viewport width.
The HTMLElement.offsetWidth read-only property returns the integer value of the width of an element. offsetWidth includes any borders, padding, and vertical scrollbars (if rendered).
const documentWidth = document.documentElement.offsetWidth
The HTMLElement.offsetHeight property can be used on an html element to determine the height of the document. Note: that the document height can be larger than the viewport height.
The HTMLElement.offsetHeight read-only property returns the integer value of the height of an element. offsetHeight includes any borders, padding, and horizontal scrollbars (if rendered).
const documentHeight = document.documentElement.offsetHeight
Browser Support: offsetWidth and offsetHeight supported by all browsers.
3. scrollWidth and scrollHeight properties
The scrollWidth property returns the width of an element, including the part that is not visible on the screen due to overflow. This is a read-only integer value that includes the element’s padding, but not its border, margin, or vertical scrollbar (if present).
const documentWidth = document.documentElement.scrollWidth
The scrollHeight property returns the height of an element, including the part that is not visible on the screen due to overflow. This is a read-only integer value that includes the element’s padding, but not its border, margin, or horizontal scrollbar (if present).
const documentHeight = document.documentElement.scrollHeight
Browser Support: scrollWidth and scrollHeight supported by all browsers.
Final thoughts
To help you understand and remember the difference think of it this way, you have a laptop (device) on which you open the browser (viewport) to view the web page (document).
Device size is always fixed, while viewport and document can change in size.
Как получить размеры экрана, окна и веб-страницы в JavaScript?
Представляю Вашему вниманию перевод небольшой заметки «How to Get the Screen, Window, and Web Page Sizes in JavaScript» автора Dmitri Pavlutin.
Для определения ориентации окна браузера (ландшафтной или портретной) можно сравнить его ширину и высоту.
Однако во всевозможных доступных размерах легко запутаться: существуют размеры экрана, окна, веб-страницы и т.д.
Что означают эти размеры и, главное, как их получить? Именно об этом я и собираюсь рассказать.
1. Экран
1.1. Размер экрана
Размер экрана — это ширина и высота всего экрана: монитора или мобильного дисплея.
Получить информацию о размере экрана можно с помощью свойства screen объекта window :
const screenWidth = window.screen.width const screenHeight = window.screen.height
1.2. Доступный размер экрана
Доступный размер экрана — это ширина и высота активного экрана без панели инструментов операционной системы.
Для получения доступного размера экрана снова обращаемся к window.screen :
const availableScreenWidth = window.screen.availWidth const availableScreenHeight = window.screen.availHeight
2. Окно
2.1. Размер внешнего окна (или внешний размер окна)
Размер внешнего окна — это ширина и высота текущего окна браузера, включая адресную строку, панель вкладок и другие панели браузера.
Получить информацию о размере внешнего окна можно с помощью свойств outerWidth и outerHeight объекта window :
const windowOuterWidth = window.outerWidth const windowOuterHeight = window.outerHeight
2.2. Внутренний размер окна (или размер внутреннего окна)
Внутренний размер окна — это ширина и высота области просмотра (вьюпорта).
Объект window предоставляет свойства innerWidth и innerHeight :
const windowInnerWidth = window.innerWidth const windowInnerHeight = window.innerHeight
Если мы хотим получить внутренний размер окна без полос прокрутки, то делаем следующее:
const windowInnerWidth = document.documentElement.clientWidth const windowInnerHeight = document.documentElement.clientHeight
3. Размер веб-страницы
Размер веб-страницы — это ширина и высота отображаемого содержимого (отрендеренного контента).
Для получения размера веб-страницы используйте следующее (включает в себя внутренние отступы страницы, но не включает границы, внешние отступы и полосы прокрутки):
const pageWidth = document.documentElement.scrollWidth const pageHeight = document.documentElement.scrollHeight
Если pageHeight больше, чем внутренняя высота окна, значит, присутствует вертикальная полоса прокрутки.
4. Заключение
Надеюсь, теперь Вы понимаете, как получать различные размеры.
Размер экрана — это размер монитора (или дисплея), а доступный размер экрана — это размер экрана без панелей инструментов ОС.
Внешний размер окна — это размер активного окна браузера (включая поисковую строку, панель вкладок, открытые боковые панели и проч.), а внутренний размер окна — это размер области просмотра.
Наконец, размер веб-страницы — это размер контента.
Благодарю за внимание, друзья!
Window screen.width
The width property returns the total width of the user’s screen.
The width property returns width in pixels.
The width property is read-only.
Note
Use the height property to get the total height of the user’s screen.
Syntax
Return Value
More Examples
let text = «Total width/height: » + screen.width + «*» + screen.height + «
» +
«Available width/height: » + screen.availWidth + «*» + screen.availHeight + «
» +
«Color depth: » + screen.colorDepth + «
» +
«Color resolution: » + screen.pixelDepth;
Browser Support
screen.width is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.