在響應式網頁設計的革命中,圖片看起來是被浪潮落下的一個事物。直到最近,根據不一樣的屏幕尺寸和像素密度來提供不一樣的圖片仍是沒有徹底實現。html
<picture>
元素展現了不少改變這個局面的但願,但不管picture元素是否能夠徹底使用,如今有兩個對於響應式圖片很關鍵的兩個屬性 —— srcset
和 sizes
。瀏覽器
srcset
屬性srcset
屬性容許咱們能夠提供一系列也許能夠被瀏覽器使用的圖片資源。咱們提供一個以逗號爲分割的圖片list,user agent會根據設備特性來決定哪一張圖片來顯示在網頁上。設計
當listing圖片時,咱們提供每張圖片兩個信息 ——code
圖片文件的_路徑_htm
圖片文件的_寬度_或者_像素密度_
爲了定義_像素密度_,咱們添加一個x
來表示圖片的密度數值。舉個栗子 —-three
<img src="one.png" srcset="two.png 2x, three.png 3x, four.png 4x"\>
在圖片 src
中定義的默認爲圖片的 1x
。圖片
在2012年srcset
屬性第一次提出時,咱們只能提供不一樣的像素密度的圖片,就像上面例子中顯示的。然而,在2014年新添加了width
屬性,它可使咱們根據不一樣的寬度來提供不一樣的圖片。資源
爲了指定圖片的寬度,咱們添加一個w
來表示圖片的像素寬度。舉個栗子 —-rem
<img src="one.png" srcset="two.png 100w, three.png 500w, four.png 1000w"\>
只有在srcset
中使用了寬度,咱們才能隨之設置sizes
屬性。get
sizes
屬性sizes
屬性明肯定義了圖片在不一樣的media conditions下應該顯示的尺寸。
<img src="one.png" srcset="two.png 100w, three.png 500w, four.png 1000w" sizes="<media condition> <width>, <media condition> <width>, <optional default image width>"\>
Media Conditions不是確切的媒體查詢。它是一部分的媒體查詢。他不容許咱們明肯定義媒體類型,好比 screen
或者 print
,可是容許咱們常常使用的媒體查詢。
可使用的有 —-
A plain media condition 好比(min-width: 900px)
A 「not」 media condition 好比( not (orientation: landscape) )
An 「and」 media condition 好比(orientation: landscape) and (min-width: 900px)
An 「or」 media condition 好比( (orientation: portrait) or (max-width: 500px) )
width
可使用任意的長度單位,好比:em, rem, pixels, 和 viewport width。
然而,百分比單位是不容許的,若是須要使用相對單位,vw
是推薦使用的。
把Media Conditions
和 width
合在一塊兒 —-
<img src="one.png" srcset="two.png 100w, three.png 500w, four.png 1000w" sizes="(min-width: 900px) 1000px,(max-width: 900px) and (min-width: 400px) 50em, ( not (orientation: portrait) ) 300px, ( (orientation: landscape) or (min-width: 1000px) ) 50vw, 100vw"\>
<iframe src="http://caniuse.bitsofco.de/embed/index.html?feat=srcset&amp;periods=future_1,current,past_1,past_2,past_3" frameborder="0" width="100%" height="473px"\></iframe\>
對於不支持這個屬性的瀏覽器,只是加載src
裏的圖片資源。