Search code examples
cssmedia-queries

Why does a css media query not match my phone


I have a bunch of media queries that load a different background image depending on the width of the screen. For some reason my One plus 2, with a screen width of 1080 in portrait is triggering the (max-width: 400px) clause. Why?

I suspect it is something to do with pixel density. If this is the case, is there a list somewhere of the most common screen sizes when taking pixel density into account?

@media screen and (max-width: 1080px) {
  .mainImage {
    background-image: url('shop-home-vertical-1080.jpg');
  }
}

@media screen and (max-width: 800px) {
  .mainImage {
    background-image: url('shop-home-vertical-800.jpg');
  }
}

@media screen and (max-width: 600px) {
  .mainImage {
    background-image: url('shop-home-vertical-600.jpg');
  }
}

@media screen and (max-width: 400px) {
  .mainImage {
    background-image: url('shop-home-vertical-400.jpg');
  }
}

Edit:

The viewport I have is:

<meta name="viewport" content="width=device-width, initial-scale=1" />

Using devtools to inspect the full width of elements on the screen. The screen width seems to be 360px. Exactly 1080 / 3.


Solution

  • This is caused by the device pixel ratio, which down scales the actual device ratio.

    Here is a list of phones and the actual display resolution used by media queries. It doesn't include the One plus two (which has a ratio of 1:3)

    The following allows me to target the one plus two accurately.

    @media screen and (max-width: 360px) and (orientation: portrait) and (min-resolution: 3dppx) {
      .mainImage {
        background-image: url('shop-home-vertical-1080.jpg');
      }
    }
    

    As I understand it. In most circumstance I shouldn't do this. But in this case it allows me to download a higher resolution image for screens that can take advantage of it.

    Just discovered that dppx is not well supported yet. This won't work on safari.