JavaScript Reference ยท Browser and Web APIs
The screen object and devicePixelRatio
Reference for window.screen and devicePixelRatio: screen size, available area, orientation, pixel density, and how they differ from the viewport.
The screen object describes the display the window is on: its size in CSS pixels, the area not covered by taskbars, its color depth and its orientation. window.devicePixelRatio tells you how many physical device pixels back each CSS pixel.
Neither tells you how much room your page has. That is the viewport, measured by window.innerWidth and window.innerHeight, or better by CSS and matchMedia(). Use screen for things like choosing the size of a popup or a canvas backing store, not for layout.
console.log(screen.width, screen.height); console.log(window.devicePixelRatio);
Try it
The values depend on your device. Compare screen.width with innerWidth: the first is the display, the second is this small preview.
Properties
| Property | Description |
|---|---|
screen.width, screen.height |
Full size of the display in CSS pixels. |
screen.availWidth, screen.availHeight |
The part not taken by system UI such as a taskbar or dock. |
screen.colorDepth, screen.pixelDepth |
Bits per pixel. In practice both are usually 24 or 30 and are kept equal. |
screen.orientation |
A ScreenOrientation with type ("landscape-primary", "portrait-primary", ...) and angle. It fires a change event. |
window.devicePixelRatio |
Device pixels per CSS pixel: 1 on standard displays, 2 or more on high-density ones, and it also changes with browser zoom. |
All of these are read-only numbers or objects. They have no methods you call for sizing; the only common action is subscribing to screen.orientation's change event.
Usage notes
- Screen is not viewport. A window can be smaller than the screen, or span several screens. Never use
screen.widthfor responsive layout. devicePixelRatiocan change while the page is open: when the user zooms or drags the window to another monitor. To react, watch a resolution media query, for examplematchMedia("(resolution: 2dppx)"), and re-read the value when it changes.- Canvas. Multiply the canvas backing size by the ratio and scale the context, as above, to avoid blurry drawing on high-density screens.
- Images. Prefer
srcsetandsizesin HTML over scripts that read the ratio. - Privacy. Screen size, depth and ratio are fingerprinting signals, and some browsers round or standardize them. Do not use them to identify users.
- Orientation lock (
screen.orientation.lock()) needs fullscreen on most browsers and is not widely available, so treat it as optional.
Browser support
screen and devicePixelRatio work in every browser. screen.orientation is supported in current browsers; the lock() method is more limited, so check a compatibility table before relying on it.