How to Detect Retina / HiDPI Displays
Learn multiple techniques to detect Retina and high-DPI displays in JavaScript and CSS, including devicePixelRatio checks and resolution media queries.
Device Pixel Ratio
Detailed Explanation
Detecting Retina Displays
Retina is Apple's branding for screens with a device pixel ratio of 2 or higher. The same concept applies to all high-DPI screens regardless of manufacturer.
JavaScript Detection
The simplest check:
const isRetina = window.devicePixelRatio >= 2;
For more granularity:
function getDisplayDensity() {
const dpr = window.devicePixelRatio || 1;
if (dpr >= 3) return 'ultra-high';
if (dpr >= 2) return 'high';
if (dpr >= 1.5) return 'mid';
return 'standard';
}
CSS Media Query Detection
Use the resolution media feature:
/* Standard approach */
@media (min-resolution: 2dppx) {
.logo { background-image: url('logo@2x.png'); }
}
/* WebKit fallback for older Safari */
@media (-webkit-min-device-pixel-ratio: 2) {
.logo { background-image: url('logo@2x.png'); }
}
Listening for DPR Changes
DPR can change when a user drags a window between monitors with different densities:
function watchDPR(callback) {
const mql = window.matchMedia(
'(resolution: ' + window.devicePixelRatio + 'dppx)'
);
mql.addEventListener('change', () => {
callback(window.devicePixelRatio);
watchDPR(callback); // re-register for the new value
});
}
Practical Considerations
- Always provide fallback images for DPR 1 screens
- Use vector formats (SVG) where possible to avoid DPR-specific assets entirely
- Test with browser DevTools device emulation to simulate different DPR values
Use Case
Web developers building image-heavy sites or pixel-perfect UIs need to detect Retina displays to serve appropriately sized assets and avoid blurry rendering on high-DPI screens.