像素宽度和高度的数量并不总是能说明问题。这对于在屏幕上添加或删除项目非常有用,但对于设置正确的图像并不完全正确。使用 MBP 上的 Retina 显示屏,设置为屏幕一半的浏览器窗口将具有与当今大多数机器相同的像素数。然而,考虑到更高的 DPI,显示的图像可能会太小。
有没有办法根据 DPI 而不是像素宽度和高度来改变图像?
像素宽度和高度的数量并不总是能说明问题。这对于在屏幕上添加或删除项目非常有用,但对于设置正确的图像并不完全正确。使用 MBP 上的 Retina 显示屏,设置为屏幕一半的浏览器窗口将具有与当今大多数机器相同的像素数。然而,考虑到更高的 DPI,显示的图像可能会太小。
有没有办法根据 DPI 而不是像素宽度和高度来改变图像?
您可以执行以下任一操作:
<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*/
}
在 2021 年,您可以在除 safari 之外的所有现代浏览器中使用媒体查询来获取分辨率、最小分辨率、最大分辨率。
header {
background-image: url(low-res-background.jpg);
}
@media (resolution >= 2dppx) {
header {
background-image: url(hi-res-background.jpg);
}
}
但 CSS 并不是唯一的答案。您也可以只使用 HTML。看看 Resposive Images withe <img srcset=...>
。
ps
您也可以使用 dpi 指定分辨率,但这仅对打印有意义:
@media print and (min-resolution: 72dpi) {
p {
text-decoration: underline;
}
}
请参阅https://developer.mozilla.org/en-US/docs/Web/CSS/@media/resolution
您正在寻找的是设备像素比率。因为像 iPhone 这样的东西显示像一个 320 像素的屏幕,但布局是 640 像素(像素比为 2)。在媒体查询中,使用“设备像素比率”。虽然我会确保仍然使用供应商前缀。
关于它的好帖子: http://menacingcloud.com/?c= highPixelDensityDisplays
也有<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。可能需要使用“最小分辨率”:
@media only screen and (min-resolution: 192dpi),
only screen and (min-resolution: 2dppx)