Get the width and height of the screen

JavaScript Window Screen

The window.screen object contains information about the user’s screen.

Window Screen

The window.screen object can be written without the window prefix.

  • screen.width
  • screen.height
  • screen.availWidth
  • screen.availHeight
  • screen.colorDepth
  • screen.pixelDepth

Window Screen Width

The screen.width property returns the width of the visitor’s screen in pixels.

Example

Display the width of the screen in pixels:

Window Screen Height

The screen.height property returns the height of the visitor’s screen in pixels.

Example

Display the height of the screen in pixels:

Window Screen Available Width

The screen.availWidth property returns the width of the visitor’s screen, in pixels, minus interface features like the Windows Taskbar.

Example

Display the available width of the screen in pixels:

Window Screen Available Height

The screen.availHeight property returns the height of the visitor’s screen, in pixels, minus interface features like the Windows Taskbar.

Example

Display the available height of the screen in pixels:

Window Screen Color Depth

The screen.colorDepth property returns the number of bits used to display one color.

All modern computers use 24 bit or 32 bit hardware for color resolution:

Older computers used 16 bits: 65,536 different «High Colors» resolution.

Very old computers, and old cell phones used 8 bits: 256 different «VGA colors».

Example

Display the color depth of the screen in bits:

The #rrggbb (rgb) values used in HTML represents «True Colors» (16,777,216 different colors)

Window Screen Pixel Depth

The screen.pixelDepth property returns the pixel depth of the screen.

Example

Display the pixel depth of the screen in bits:

For modern computers, Color Depth and Pixel Depth are equal.

Источник

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

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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.

Источник

Как получить размеры экрана, окна и веб-страницы в 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. Заключение

Надеюсь, теперь Вы понимаете, как получать различные размеры.

Размер экрана — это размер монитора (или дисплея), а доступный размер экрана — это размер экрана без панелей инструментов ОС.

Внешний размер окна — это размер активного окна браузера (включая поисковую строку, панель вкладок, открытые боковые панели и проч.), а внутренний размер окна — это размер области просмотра.

Наконец, размер веб-страницы — это размер контента.

Благодарю за внимание, друзья!

Источник

How to get current screen width in css in Html?

HTML is a markup language used to structure and display content on the web. CSS, or Cascading Style Sheets, is used to control the layout and appearance of elements on a web page.

To get the current screen width in CSS, there are a few different methods that can be used. Here are three examples:

Method 1: Using the width property

For example, if you want to target the body element, you would add the following code to your CSS file:

In this example, we are setting the width of the body element to 100%, which will make it the same width as the screen.

Method 2: Using JavaScript

For example, if you want to target the body element, you would add the following code to your HTML file:

var screenWidth = window.innerWidth;
  • Step 3 — Use the getElementById method to target the element you want to set the width of, and the style property to set the width
document.getElementById("myBody").style.width = screenWidth + "px";

This will set the width of the element with the id «myBody» to the current screen width.

Method 3: Using media queries

This media query will apply the CSS inside the curly braces only when the screen width is 600px or less.

@media (max-width: 600px) < body < width: 100%; >> @media (min-width: 601px) and (max-width: 900px) < body < width: 80%; >>

This will set the width of the body element to 100% when the screen width is 600px or less, and 80% when the screen width is between 601px and 900px.

These are just a few examples of how to get the current screen width in CSS. Depending on your specific use case and the tools you are using, there may be other methods that are more appropriate. The important thing is to understand the concepts behind each method, and how to apply them to your specific project.

It is worth noting that the method you choose will depend on what you are trying to achieve and the tools you are using. The width property method is a simple and straight forward method that doesn’t require any additional tools or libraries, and is supported by all modern browsers. However, it has a limitation in that it can only be used to set the width of a single element.

The JavaScript method is a more dynamic and flexible method that can be used to set the width of multiple elements and can be combined with other JavaScript code to create more complex interactions. However, it does require some knowledge of JavaScript and can be more complex to implement.

The media query method is a powerful tool that allows you to create responsive designs that adjust to different screen sizes. This method is also supported by all modern browsers, but it can be complex to implement if you have many different screen sizes to target.

In any case, It’s important to note that these examples are not the only ways to get current screen width in CSS, and there are other ways to achieve this.

For example, you can use libraries such as Bootstrap, Foundation or Bulma, which are pre-made collections of CSS and JavaScript that can help you quickly create responsive designs.

In addition, you can use the CSS variables(custom properties) to store the width and use it across your css.

It’s a good practice to try different ways and choose the one that best fits your project’s requirements.

Conclusion

To summarize, there are several ways to get the current screen width in CSS, including using the width property, JavaScript, and media queries. Each method has its own advantages and limitations, and the choice of which method to use will depend on the specific requirements of your project. The width property method is a simple and straightforward method that is supported by all modern browsers, while the JavaScript method is more flexible and dynamic but requires some knowledge of JavaScript. The media query method is a powerful tool for creating responsive designs that adjust to different screen sizes but can be complex to implement. Additionally, you can use pre-made libraries such as Bootstrap, Foundation, or Bulma, or even CSS variables to store and use the width across your CSS. It’s a good practice to try different approaches and choose the one that best fits your project’s requirements.

Источник

How to get the Width and Height of the screen in JavaScript?

In this article, we are going to discuss how to get the width and height of the screen in JavaScript.

Javascript provides an window.screen object that contains information regarding the user’s screen. The information includes height and width, and also many other features.

To find the height and width of the screen you need to use the following read-only properties

  • Screen.height − This property is used to get the height of the screen in pixels.
  • Screen.width − This property is used to get the width of the screen in pixels.

Syntax

Following is the syntax of the height to get the height and with of a screen respectively −

Example 1

In the following example, the width of the screen is displayed using the screen.width method.

      

Example 2

In the following example, the height of the screen is displayed using the screen.height method.

      

Example 3

In the following example we are trying to get the width and height of the screen using the screen.width and screen.height properties −

         

Example 4

Following is another example of this −

         

Источник

Читайте также:  Python количество секунд datetime
Оцените статью