JS Screen
JavaScript screen Object: Display Size and Pixel Density
The JavaScript window.screen object exposes dimensions and color metrics of the user's physical monitor or mobile screen. Combining screen properties with window.devicePixelRatio helps canvas graphics, full-screen video players, and analytics understand display hardware.
Key screen and Display Properties
screen.width/screen.height: Total width and height of the user's display in CSS pixels.screen.availWidth/screen.availHeight: Usable screen space after subtracting OS taskbars, macOS docks, or system menus.screen.colorDepth/screen.pixelDepth: Bit depth per pixel (usually24or32on modern monitors).window.devicePixelRatio: Ratio of physical device pixels to CSS pixels (2on Retina displays)—essential for crisp<canvas>rendering.screen.orientation?.type: Reports"landscape-primary"or"portrait-primary"on tablets and phones.
Practical Screen and Canvas DPR Example
Never use screen.width for responsive page layouts, because a user on a 2560px monitor may resize their browser window to 600px wide! Use window.innerWidth or CSS media queries for layout, and devicePixelRatio for sharp graphics.
const metrics = {
screenSize: `${screen.width}x${screen.height}`,
availableSize: `${screen.availWidth}x${screen.availHeight}`,
viewportSize: `${window.innerWidth}x${window.innerHeight}`,
dpr: window.devicePixelRatio || 1,
orientation: screen.orientation?.type ?? "unknown",
};
console.log("Display metrics:", metrics);
Common Mistakes to Avoid
- Using
screen.widthinstead ofwindow.innerWidthfor layout decisions:screen.widthmeasures the entire physical monitor even when the browser window occupies half the screen. - Blurring
<canvas>drawings on Retina screens: Drawing onto a400x200canvas without scaling bywindow.devicePixelRatiomakes lines and text look fuzzy on HiDPI displays. - Trusting
screenproperties for user fingerprinting: Modern privacy browsers like Safari and Firefox may spoof or roundscreenvalues to limit cross-site tracking.
Frequently Asked Questions
Why is screen.availHeight smaller than screen.height?
screen.availHeight subtracts fixed operating system panels such as the Windows taskbar or macOS Dock.
How do I detect when a mobile user rotates their phone?
Attach a listener with screen.orientation?.addEventListener("change", () => ...) or listen to window.matchMedia("(orientation: portrait)").
What is the difference between screen.width and document.documentElement.clientWidth?
screen.width is the hardware monitor width, whereas document.documentElement.clientWidth is the usable inner page width inside the browser window excluding scrollbars.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.