HTML & CSS Interview Question #47

What is the picture element and when should it be used?

Forms, Validation, Metadata, Media, Responsive Images & Accessibility Mid-Level Intermediate

Quick Interview Answer

picture lets developers provide different image sources based on media conditions or supported image formats. The browser evaluates source elements and falls back to the nested img element when necessary.

Detailed Explanation

picture lets developers provide different image sources based on media conditions or supported image formats. The browser evaluates source elements and falls back to the nested img element when necessary.

It is useful for art direction, such as using a different crop on mobile, and for offering modern formats with a fallback. For simple resolution switching of the same image, srcset and sizes on img may be sufficient.

Code Example

<picture>
    <source media="(max-width: 600px)"
            srcset="product-mobile.jpg">

    <source type="image/webp"
            srcset="product.webp">

    <img src="product.jpg"
         alt="Portable projector">
</picture>