Explain Codes LogoExplain Codes Logo

How to detect the screen resolution with JavaScript?

javascript
responsive-design
promises
callbacks
Anton ShumikhinbyAnton Shumikhin·Feb 16, 2025
TLDR

You can easily detect the screen resolution with window.screen.width for width and window.screen.height for height:

// Because we all like knowing our monitor's size in pixels! console.log(`Waddup, your screen resolution is: ${window.screen.width}x${window.screen.height}`);

This outputs the resolution as width by height, giving you the overall screen resolution in a convenient format.

Crucial Bifurcations: Absolute Dimensions vs. Available Screen

Getting absolute screen size

let totalWidth = window.screen.width; // Complete width let totalHeight = window.screen.height; // Complete height

The variables totalWidth and totalHeight fetch the absolute dimensions of your screen, akin to asking a monitor "How big are you in pixels, honestly?".

Deriving available screen size

But, how about the usable screen space? Well, availWidth and availHeight play this role:

let usableWidth = window.screen.availWidth; // Width minus the OS taskbar etc. let usableHeight = window.screen.availHeight; // Height minus the browser toolbar etc.

Mobile Devices & Their Fond love for Pixel Ratio

If you're dealing with mobile devices, pixel density affects screen resolution, like when your phone brags about the super retina display!

// Mobile devices showing off their high resolution, as always! let devicePixelRatio = window.devicePixelRatio || 1; let actualWidth = totalWidth * devicePixelRatio; let actualHeight = totalHeight * devicePixelRatio;

Here, devicePixelRatio handles differences between CSS pixels and device pixels, great when you need accurate screen information for media queries or responsive design.

Understanding Viewport Dimensions

Sometimes, what matters is not the entire screen but the part of it where your web page is visible, which is our good ol' viewport:

let viewportWidth = window.innerWidth; let viewportHeight = window.innerHeight;

These little fellows return the viewable area, unobstructed by browser toolbars and scrollbars. A classic case of "I'm here only for the content, ads you can keep to yourself!".

From 10,000 Feet: Other Aspects of Screen Resolution

Web designers make an assumption on a standard 72 dpi resolution. However, Javascript doesn't provide a physical resolution, only the pixel count, crucial for responsive designs.

Do note, non-square pixels, although rare, aren't considered in JavaScript resolution detection. Plus, the physical screen size remains unknown to your browser and JavaScript.

For jQuery users, $(window).width() and $(window).height() can be used to offer similar functionality.