Search code examples
htmlimagemedia-queries

HTML picture tag with media queries and multiple file formats


I am planning to start using HTML picture tags on my website. I know that with picture tags, it is possible to use media queries and serve differently-sized images and different file formats. But are the following things possible?

  • To have 6 different image sizes both as jpeg and webp. The browser should prefer webp and jpeg versions to be served only as secondary options.
  • As I understand, media queries are against the viewport width. Would there be any easy way to have a query against the current container width? For example, the viewport can be 1200px but the image's container only be 600px. In that case, serving 1200px wide image would be a waste of bandwidth.

Solution

  • The <picture> element can be used to provide alternative sources for an image. It must have a default <img> element.

    From top to bottom, the first matching and supported <source> element's source will be used instead of the fallback image's. If you want to prefer WebP over JPEG, simply list the WebP <source>s first:

    <picture>
      <source srcset="alternative.webp" type="image/webp">
      <source srcset="alternative.jpeg" type="image/jpeg">
      <img src="default.png">
    </picture>
    

    As for querying against the container: I believe this is currently not possible.

    Ideally, the page is designed in a way where you (as the designer) know how the elements will be sized. If this is not the case, you can still estimate what sources to serve for certain sizes.

    I highly recommend to read MDN's Responsive images article. In short, you should use the following:

    • Attribute srcset: A list of all alternative sources along with either their intrinsic widths or pixel density descriptors only.
    • Attribute sizes: A list of media queries and the resulting slot sizes.

    Note: The px unit in the sizes attribute refers to "CSS pixels". These CSS pixel don't refer to actual device pixel; they refer to virtual pixels that are scaled to be reasonably sized for the device. (Related: The Viewport meta tag.)

    The browser will calculate which source to use based on the source's and the slot's size, while considering the scale between device and CSS pixels.

    Or in other words: With the information given via the attributes, the browser will choose the highest-quality image for your media (i.e. screen).


    At a glance, I also found the blog Responsive images by KeyCDN informative.