Is there a way to use DPI in css media queries ins

2020-02-19 06:55发布

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条回答
萌系小妹纸
2楼-- · 2020-02-19 07:32

What you are looking for is the Device Pixel ratio. Because things like the iPhone display like a 320px screen but with a 640px layout (Pixel ratio of 2). In media queries, use "device-pixel-ratio". Though I would make sure to still use the vendor prefixes.

A good post on it: http://menacingcloud.com/?c=highPixelDensityDisplays

查看更多
▲ chillily
3楼-- · 2020-02-19 07:49

You can do either:

<link
    rel="stylesheet"
    type="text/css"
    href="/css/retina.css"
    media="only screen and (-moz-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)"
/>

or

@media only screen and (-moz-min-device-pixel-ratio: 2), 
       only screen and (-o-min-device-pixel-ratio: 2/1), 
       only screen and (-webkit-min-device-pixel-ratio: 2), 
       only screen and (min-device-pixel-ratio: 2) {
 /*use CSS to swap out your low res images with high res ones here*/
}   
查看更多
\"骚年 ilove
4楼-- · 2020-02-19 07:49

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

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

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

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-02-19 07:53

There are also <img srcset> and -webkit-image-set css function, but they seem to be supported only by Safari/Chrome/Opera. Example:

<img src="image.png" srcset="image-1x.png 1x, 
     image-2x.png 2x, image-3x.png 3x">

background-image:  -webkit-image-set(
     url(icon1x.jpg) 1x,
     url(icon2x.jpg) 2x
);

I'm not sure if the examples in the accepted answer by Moin Zaman work on IE/Firefox. Probably "min-resolution" needs to be used:

@media only screen and (min-resolution: 192dpi),
       only screen and (min-resolution: 2dppx)
查看更多
登录 后发表回答