像素宽度和高度并不总是能完全说明问题。这种方法在屏幕上添加或删除项目非常适用,但对于设置正确的图像就不太合适了。在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);
}
}
<img srcset=...>
的响应式图片。@media print and (min-resolution: 72dpi) {
p {
text-decoration: underline;
}
}
请查看https://developer.mozilla.org/zh-CN/docs/Web/CSS/@media/resolution
还有<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)
min--moz-device-pixel-ratio
。 - andreasbovens