有没有办法在css媒体查询中使用DPI而不是px

Den*_*ton 18 css media-queries

像素宽度和高度并不总能说明整个故事.这适用于在屏幕上添加或删除项目,但不适合设置正确的图像.使用MBP上的视网膜显示器,设置为屏幕一半的浏览器窗口将具有与当今大多数机器相同的像素宽度.然而,考虑到较高的DPI,显示的图像可能太小.

有没有办法根据DPI更改图像而不是像素宽度和高度?

Moi*_*man 20

你可以这样做:

<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)"
/>
Run Code Online (Sandbox Code Playgroud)

要么

@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*/
}   
Run Code Online (Sandbox Code Playgroud)


bje*_*lli 7

自 2022 年起,您可以在所有现代浏览器中使用媒体查询来获取分辨率、最小分辨率、最大分辨率。

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

但 CSS 并不是唯一的答案。您也可以只使用 HTML。看看带有 的响应图像<img srcset=...>

附注

您还可以使用 dpi 来指定分辨率,但这仅对打印有意义:

@media print and (min-resolution: 72dpi) {
  p {
    text-decoration: underline;
  }
}
Run Code Online (Sandbox Code Playgroud)

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