Practical use cases for the picture element
The brave new world of responsive images has already been explored and explained in great detail all over the web (see resource list below). Most of these resources advise against using the <picture/>
element for standard images since it’s far more declarative and doesn’t allow the browser to automagically choose an image based on the user’s network and screen resolution. (hint: srcset does this, so use this method when including images you don’t need declarative control over.) If a majority of the web agrees that the <img/>
tag accompanied with the new srcset and sizes attributes is the most pragmatic solution where does that leave the poor ‘ol <picture/>
element? 😥
The stand alone <img/>
and srcset
method trumps in all cases except art direction and type-switching fallback support. This post simply showcases these two use cases for quick reference and experimentation. For more information on the <picture/>
element and the responsive images spec, refer to the list of resources below.
Art direction
The most pragmatic use case for the <picture/>
element is art direction. The srcset
and media
attributes give you full control of serving different images to various viewport sizes. This comes in handy when you need to serve cropped, or different sized images to multiple viewports for art directed media or for readability purposes.
<picture>
<!---[if IE 9]><video style="display: none;"><![endif]-->
<source srcset="/image-full.jpg" media="(min-width: 1024px)">
<source srcset="/image-close.jpg" media="(min-width: 768px)">
<!---[if IE 9]></video><![endif]-->
<img src="/image-closer.jpg" alt="Image Description"/>
</picture>
Resize your browser window and notice how cropped and resized versions are served as you resize to a smaller viewport. Notice how declarative the picture method is? Giving it a new media source at different media queries makes for a practical solution for art direction.
Type switching
The <picture/>
spec provides a type
attribute that you can use on any nested <source/>
element. This provides you with a viable fallback solution for older browser that don’t support new images formats, e.g., .webp
, .svg
.
<picture>
<!--[if IE 9]><video style="display: none;"><![endif]-->
<source srcset="/pattern-example.svg" type="image/svg xml">
<!--[if IE 9]></video><![endif]-->
<img src="/pattern-example.png" alt="Image Description"/>
</picture>
Resource list
- When Responsive Images Get Ugly
- Srcset and sizes
- Don’t Use Picture Most of the Time
- Better SVG Fallback and Art Direction With The picture Element
- Responsive Images: If you’re just changing resolutions, use srcset
- Responsive Images Done Right: A Guide To
- Use Cases and Requirements for Standardizing Responsive Images
- Spec