Detect scale settings (dpi) with JavaScript or CSS

I've noticed that a small laptop with a 1920x1080 screen, windows 10 will auto adjust the scaling. I've seen it as high as 150%. Is there a way we can detect this? My media queries don't kick in as they're set in px.

Asked By: Mark Handy
||

Answer #1:

Try accessing window.devicePixelRatio variable.

The Window property devicePixelRatio returns the ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device. This value could also be interpreted as the ratio of pixel sizes: the size of one CSS pixel to the size of one physical pixel. In simpler terms, this tells the browser how many of the screen's actual pixels should be used to draw a single CSS pixel.

More info about it: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio

You could also use CSS resolution for this, more about this here: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/resolution

@media (resolution: 150dpi) {
  p {
    color: red;
  }
}
Answered By: Martin Adámek

Answer #2:

For anyone looking into this, building a little on Martin Adamek's answer, you can do this in jQuery and scale something with CSS transform:

// if the user has display scaling active, scale with CSS transform    
if (window.devicePixelRatio !== 1){
    let scaleValue = (1/window.devicePixelRatio);
    $('#containerToBeScaled').css('transform','scale('+scaleValue+')');
}

This works well if you have a pop-Up for example and you want it to look the same regardless of display scaling

Answered By: Stefan S

Answer #3:

This isn't specifically what OP asked for, but what I think a lot of users landing on this question will be asking..

150% text scaling in Windows 10 is breaking my webpage, what can I do about it?

Approach

  1. First, make sure you're using rem for font-sizing on the problem text. rem is designed for this situation.
  2. Now you can scale ALL text at once with a single media query from the root html element.

This avoids any CSS transform scaling which inevitably results in a blurry result.

HTML root media query

    /* Handle 125% and 150% Windows 10 Font Scaling on 96dpi monitors */
    @media (min-resolution: 120dpi) {
        html {
             font-size: 80%;
        }
    }

Adjust the 80% to your liking, less = smaller text

Note: Be aware that 150% scaling doesn't mean 150dpi. Most monitors are either 72dpi or 96dpi. So, 150% scaling would mean 108dpi or 144dpi as the min-resolution you're querying.

rem Font-Sizing

And make sure you're using rem for fonts, for example:

    p {
        font-size: 1rem;
    }

If you're using px, you don't have to change everything, just do it for the text that is causing issues.

Answered By: Chris Hayes
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles