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

孤街醉人 提交于 2019-12-18 11:49:54

问题


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?


回答1:


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*/
}   



回答2:


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




回答3:


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)



回答4:


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



来源:https://stackoverflow.com/questions/11722442/is-there-a-way-to-use-dpi-in-css-media-queries-instead-of-px

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!