有没有一种方法可以在CSS媒体查询中使用DPI而不是像素(px)?

26

像素宽度和高度并不总是能完全说明问题。这种方法在屏幕上添加或删除项目非常适用,但对于设置正确的图像就不太合适了。在MBP上的Retina显示器中,将浏览器窗口设置为屏幕的一半时,其宽度上的像素数与今天大多数机器相同。然而,由于更高的DPI,显示的图像可能会过小。

有没有一种方法可以根据DPI而不是像素宽度和高度来更改图像呢?

4个回答

24
你可以选择以下方法之一:
<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)"
/>
或者
@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*/
}   

我认为应该是 min--moz-device-pixel-ratio - andreasbovens

6

在2021年,除了Safari浏览器外,在所有现代浏览器中,您都可以使用媒体查询来设置分辨率、最小分辨率和最大分辨率。

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

但是CSS并不是唯一的答案。你也可以使用HTML。看一下带有<img srcset=...>的响应式图片。
顺便说一下,你也可以使用dpi来指定分辨率,但这只对打印有意义。
@media print and (min-resolution: 72dpi) {
  p {
    text-decoration: underline;
  }
}

请查看https://developer.mozilla.org/zh-CN/docs/Web/CSS/@media/resolution


这不起作用。显示器是72dpi还是96dpi都无关紧要 - 你需要查询的是渲染单个软件像素所使用的多少硬件像素。例如,iPhone可能使用一个、四个或九个像素来渲染单个像素方形图像。如果用户的显示器使用九个像素来渲染每个“像素”,那么给用户提供高分辨率的背景图像会很好,但你不希望所有用户都受到这种影响,因为9倍的图像数据不仅浪费带宽,而且在缩放到较低分辨率的显示器时也会变得模糊。 - Abhi Beckert
@AbhiBeckert - 你是对的,我编辑了我的回答以便聚焦于分辨率:dppx - bjelli

2
您需要查找的是设备像素比。因为像 iPhone 显示器一样的屏幕,其显示宽度为 320px,但布局为 640px(像素比为 2)。在媒体查询中使用 "device-pixel-ratio"。尽管我建议仍然使用供应商前缀。
这里有一篇关于此主题的好文章:http://menacingcloud.com/?c=highPixelDensityDisplays

1

还有<img srcset>-webkit-image-set CSS函数,但它们似乎只受Safari/Chrome/Opera支持。例如:

<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
);

我不确定Moin Zaman所提供的被接受答案中的示例是否适用于IE/Firefox浏览器。可能需要使用"min-resolution"。

@media only screen and (min-resolution: 192dpi),
       only screen and (min-resolution: 2dppx)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接