2012-07-30 23 views
17

像素數量的寬度和高度並不總是說明整個故事。這對於添加或刪除屏幕上的項目非常有用,但對於設置正確的圖像並不太合適。通過MBP上的視網膜顯示,設置爲屏幕一半的瀏覽器窗口的寬度像現在的大多數機器一樣。然而,鑑於DPI較高,顯示的圖像可能會太小。有沒有辦法在css媒體查詢中使用DPI而不是px

有沒有一種方法可以根據DPI更改圖像而不是像素數量的寬度和高度?

回答

19

您可以執行:

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

我相信它應該是'min-moz-device-pixel-ratio' – andreasbovens 2014-12-19 10:41:12

2

你要找的是設備像素比例。因爲像iPhone這樣的顯示器就像一個320像素的屏幕,但具有640像素的佈局(像素比爲2)。在媒體查詢中,使用「device-pixel-ratio」。雖然我會確保仍然使用供應商前綴。

好的帖子就可以了:http://menacingcloud.com/?c=highPixelDensityDisplays

1

也有<img srcset>-webkit-image-set CSS功能,但他們似乎是通過Safari /鉻/歌劇僅支持。示例:

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