(译)响应式图片— srcset 和 sizes 属性

在响应式网页设计的革命中,图片看起来是被浪潮落下的一个事物。直到最近,根据不一样的屏幕尺寸和像素密度来提供不一样的图片仍是没有彻底实现。html

<picture>元素展现了不少改变这个局面的但愿,但不管picture元素是否能够彻底使用,如今有两个对于响应式图片很关键的两个属性 —— srcsetsizes浏览器

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

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

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;amp;periods=future_1,current,past_1,past_2,past_3" frameborder="0" width="100%" height="473px"\></iframe\>

对于不支持这个属性的浏览器,只是加载src里的图片资源。

译自:Responsive Images - The srcset and sizes Attributes

相关文章
相关标签/搜索