Is there a way to use DPI in css media queries instead of px

Viewed 45903

Number of pixels width and height does not always tell the whole story. That works great for adding or removing items from the screen, but isn't quite right for setting the right image. With the retina display on the MBP, a browser window set to half of the screen would have the same number of pixels in width as most machines today. Yet, images displayed would likely be too small given the higher DPI.

Is there a way to change out images based on DPI rather than the number of pixels width and height?

4 Answers

In 2021 you can use a media query for resolution, min-resolution, max-resolution in all modern browsers except safari.

header {
  background-image: url(low-res-background.jpg);
}
@media (resolution >= 2dppx) {
  header {
    background-image: url(hi-res-background.jpg);
  }
}

But CSS is not the only anwer. You can also just use HTML. Have a look at Resposive Images withe <img srcset=...>.

p.s.

You could also use dpi to specify resolution, but this only makes sense for print:

@media print and (min-resolution: 72dpi) {
  p {
    text-decoration: underline;
  }
}

See https://developer.mozilla.org/en-US/docs/Web/CSS/@media/resolution

Related