Frontend Scrapbook

Notes that make a difference

picture element vs img tag

By admin

on Tue Aug 25 2020

Per specification, the picture element is an image container whose source element is determined by one or more css media queries. The picture element’s use of media queries make it easy to serve variations of images ( not just the size ) that pair with visual breakpoints in a CSS layout.

Picture element contains a series of source elements followed by a img element. A browser will iterate over the source elements in order of appearance and stop when it encounters a source with matching media attribute, then set the img element’s source to a URL specified in the source element’s srcset attribute. If no source elements end up matching, the img element’s own attributes ( say, srcset ) will be used to determine its source.

srcset is a attribute designed to contain one or more potential source URLs for an image.It ask the browser to decide the most appropriate asset based on any criteria the browser deems relevant.

Unless you are trying to pair the sources of an image with media query breakpoints in a layout, you probably don’t need picture element.

The sizes attribute to picture’s source element and img element lets us suggest the size at which an image will be rendered in the layout at a given media query breakpoint

sizes=”(max-width:30em) 100%, 50%”

Above means, when the viewport is 30em or narrower, image width will be 100% viewport’s width. If the viewport width is wider than 30em, image width will be 50% of viewport’s width. Note that these are merely cues to all the browser to render the image, which helps prevent reflows as the page layout is drawn.

<source srcset=“med.webp” type=“image/wep” >

If the browser supports the type format, browser will use that type.