Coastal Media Brand

The HTML <picture> element displays responsive images on web pages. It allows web developers to provide multiple sources of an image, specifying different versions for various screen sizes or resolutions.

This ensures that the most suitable image is loaded for each user’s device, optimizing performance and user experience.

Syntax

The <picture> element consists of one or more <source> elements nested inside it, followed by an <img> element for fallback content. Here’s a basic example of the syntax: 

1
<picture>
2
  <source srcset="image-large.jpg" media="(min-width: 800px)">
3
  <source srcset="image-medium.jpg" media="(min-width: 400px)">
4
  <img src="image-small.jpg" alt="A responsive image">
5
</picture>

In this example, three different versions of an image are provided. The browser will choose the most appropriate one based on the viewport size calculated at a min-width media size.

Examples

Art Direction

1
<picture>
2
  <source srcset="portrait.jpg" media="(orientation: portrait)">
3
  <source srcset="landscape.jpg" media="(orientation: landscape)">
4
  <img src="default.jpg" alt="An image with art direction">
5
</picture>

Here, images are selected based on the device’s orientation, ensuring the correct image is displayed for portrait and landscape views. A design may take a different form depending on the device’s orientation to view the content.

Check out the full-screen version and resize the browser to see the image selection in action.

Notice how the <source> elements are bringing the images in, but we still use the img {} selector to target each one with CSS.

High-DPI Displays

1
<picture>
2
  <source srcset="image.jpg" type="image/jpeg">
3
  <source srcset="image@2x.jpg 2x" type="image/jpeg">
4
  <img src="image.jpg" alt="A high-DPI image">
5
</picture>

This example targets high-DPI (Retina) displays by providing a 2x resolution image with the @2x suffix.

It’s important to note that the @2x suffix in the srcset attribute does not trigger the browser’s high-DPI (Retina) display recognition. The @2x convention is commonly used in file naming to indicate higher pixel density or resolution versions of images for the benefit of developers and designers. Consider it a design pattern.

Attributes

The <picture> element supports global attributes.

Content

The <picture> element accepts multiple <source> elements followed by an <img> element for fallback content. Each <source> element should have a srcset attribute, and the <img> element should have a src and alt attribute.

Did You Know?

  • The <picture> element was introduced in HTML5 to address the need for responsive images in web design.
  • Web developers can combine <picture> with the <source> and <img> elements to create adaptive images for modern websites.

Learn More

Web Design Myrtle Beach

Coastal Media Brand

© 2024 Coastal Media Brand. All rights Reserved.