JS Screen
window.screen describes the physical display the browser is showing on — useful for adaptive layouts beyond viewport.
Properties
| Property | Returns |
|---|---|
screen.width / height | Total screen pixels. |
screen.availWidth / availHeight | Minus dock / taskbar. |
screen.colorDepth / pixelDepth | Bit-depth (24 = 16M colours). |
screen.orientation | Object with type and angle. |
window.devicePixelRatio | Physical-to-CSS pixel ratio (2 on Retina). |
Better signals for layout
| Question | Use |
|---|---|
| How wide is the viewport? | window.innerWidth or matchMedia — NOT screen.width |
| Should I serve a 2× image? | window.devicePixelRatio >= 2 or srcset |
| Is the device in landscape? | screen.orientation?.type.startsWith("landscape") |
| Coarse pointer (touch)? | matchMedia("(pointer: coarse)").matches |
Orientation change
JS
screen.orientation.addEventListener("change", () => {
console.log("now", screen.orientation.type, screen.orientation.angle);
});
Privacy: screen properties are part of the browser fingerprinting surface. Don't read them unless you actually need them for layout.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Screen!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Detect a high-DPI display.
if (window.
>= 2) loadRetinaImage();
Three words concatenated, camelCase.
Discussion
Loading…