HTML Picture Element

HTML element <picture> can be used to define different images for different screen sizes or devices.

The picture element includes one or more <source> elements, each linking to a different image using the attribute srcset and attribute media to define the device size as below.

<picture>
    <source media="(min-width: 800px)" srcset="image_one.jpg">
    <source media="(min-width: 600px)" srcset="image_two.jpg">
    <source media="(min-width: 400px)" srcset="image_three.jpg">
    <img src="image_default.jpg" alt="default-image">
</picture>

In the above example, three different screen sizes are defined along with a default image, which works as below.

  • image_one.jpg is displayed when the screen width >= 800px
  • image_two.jpg is displayed when the screen width >= 600px and width < 800px
  • image_three.jpg is displayed when the screen width >= 600px and width < 600px
  • image_default.jpg is displayed when none of the sources match or is found, which should always be the last child of the picture element

Example

<!doctype html>
<html lang="en">
<head>
</head>
<body>
    <h1>HTML Picture Element</h1>
    <h2>Determining source using min width</h2>
    <picture>
        <source media="(min-width: 800px)" srcset="/assets/images/image_one.jpg">
        <source media="(min-width: 600px)" srcset="/assets/images/image_two.jpg">
        <source media="(min-width: 400px)" srcset="/assets/images/image_three.jpg">
        <img src="/assets/images/image_default.jpg" alt="default-image">
    </picture>
    <h2>Determining source using max width</h2>
    <picture>        
        <source media="(max-width: 400px)" srcset="/assets/images/image_three.jpg">
        <source media="(max-width: 600px)" srcset="/assets/images/image_two.jpg">
        <source media="(max-width: 800px)" srcset="/assets/images/image_one.jpg">
        <img src="/assets/images/image_default.jpg" alt="default-image">
    </picture>
</body>
</html>

Overall

The HTML picture element can be used to display different images for different screen sizes using the same placeholder element.