JavaScript: Get screen width and height (resolution)
How to get the screen width and height using JavaScript#
The screen resolution of a device can be determined using the screen
object. screen.width
returns the width of the screen, while screen.height
returns the height of the screen.
<div id="screen">
<div id="screen-info">Your screen resolution</div>
<div>Width: <span id="Width"></span></div>
<div>Height: <span id="Height"></span></div>
<div>Pixel depth: <span id="Pixel"></span></div>
.applet {
background: #f5f5f5;
}
.applet-body {
padding: 10px;
}
#screen {
text-align: center;
}
#screen-info {
font-size: 19px;
margin-bottom: 15px;
}
#screen span {
font-style: italic;
}
document.querySelector('#Width').innerText = screen.width + 'px';
document.querySelector('#Height').innerText = screen.height + 'px';
document.querySelector('#Pixel').innerText = screen.pixelDepth;
You may want to determine a user's screen size for various purposes. Eg: extended features for users with large monitors, optimized behavior and functionality on devices with less width and height, etc.
Note that, screen resolution or the width and height of the screen is different from browser window dimensions. A user with a screen resolution of 2560x1440 may have the browser window resized to 1280x720. For window dimensions refer to /webdev/javascript/browser-window-width-height.html.
Summary#
screen.width
returns the width of the monitor screen. screen.height
returns the height of the monitor screen.