Responsive images

The new thing with the <picture> tags are that they explain the browser about images and let the browser decide which one to use.

Explanation of the tags:
  • <picture> Wraps all the picture tags.
  • <src> Used as a fallback for old browsers.
  • <srcset> Tells the browser the sizes of images.
  • <sizes> Tells the browser the sizes the image actually are beeing used.
  • <source media> Different image sources, controlled with media queries.
  • Browser support: These new tags are only supportet in Chrome (38) and Opera (25), but using the Picturefill.js it will work in most browsers.

    Full width images

    Only use <srscet> for full width images. The browser will pick the images corresponding to the viewport size.

    See code

    <picture>
    <img src="img/medium.jpg"
    srcset="img/small.jpg 640w,
    img/medium.jpg 1024w,
    img/large.jpg 2000w"
    alt="Moonlanding." />
    </picture>

    Moonlanding.

    Fixed size (700px)

    For image that are use in a specific size use <sizes> to explain the browser the size the image are being used and the browser will choose the most suited image from your <srscet>.

    See code

    <picture>
    <img src="img/medium.jpg"
    srcset="img/small.jpg 640w,
    img/medium.jpg 1024w,
    img/large.jpg 2000w"
    sizes="(min-width: 720px) 700px, 100vw"
    alt="Moonlanding." />
    </picture>

    Moonlanding.

    Image with different source on small screens

    To add a whole different images on a specified occation use <media> to add a different <srscet>. It can be controlled with media queries.

    See code

    <picture>
    <source
    media="(min-width: 800px)"
    srcset="img/small.jpg 640w,
    img/medium.jpg 1024w,
    img/large.jpg 2000w"
    <source
    srcset="img/large-square.jpg" />
    <img
    src="img/medium.jpg"
    alt="Moonlanding." />
    </picture>

    Moonlanding.

    All together

    The cool thing are that all these tags can be used together.

    See code

    <picture>
    <source
    media="(min-width: 800px)"
    srcset="img/small.jpg 640w,
    img/medium.jpg 1024w,
    img/large.jpg 2000w"
    <source
    srcset="img/large-square.jpg" />
    sizes="(min-width: 720px) 700px, 100vw"
    <img
    src="img/medium.jpg"
    alt="Moonlanding." />
    </picture>

    Moonlanding.