Syntax for Responsive Images | Responsive Images

The most common method for implementing responsive images involves using the srcset and sizes attributes.

srcset Attribute

  • Specifies a list of image sources and their corresponding sizes.
  • Each source is separated by a comma.
  • The size is specified in pixels followed by the letter w.

Syntax:

HTML

<img src=”image.jpg” alt=”Image” srcset=”image-small.jpg 320w, image-medium.jpg 640w, image-large.jpg 1280w”>

sizes Attribute

  • Defines the width of the image in various viewport widths.
  • Each size is separated by a comma.

Syntax:

HTML

<img src=”image.jpg” alt=”Image” srcset=”image-small.jpg 320w, image-medium.jpg 640w, image-large.jpg 1280w” sizes=”(max-width: 320px) 320px, (max-width: 640px) 640px, 100vw”>

Example:

HTML

<img src=”image.jpg” alt=”Image” srcset=”image-small.jpg 320w, image-medium.jpg 640w, image-large.jpg 1280w” sizes=”(max-width: 320px) 320px, (max-width: 640px) 640px, 100vw”>

In this example:

  • srcset: Provides three image sources with corresponding widths.
  • sizes: Defines the image width for different viewport widths.

Using the picture Element

The picture element offers more granular control over responsive images.

Syntax:

HTML

<picture>

  <source srcset=”image-small.jpg 320w” media=”(max-width: 320px)”>

  <source srcset=”image-medium.jpg 640w” media=”(max-width: 640px)”>

  <img src=”image-large.jpg” alt=”Image”>

</picture>

Best Practices

  • Optimize image sizes: Create different image sizes to match common screen resolutions.
  • Use appropriate image formats: Choose the best image format (e.g., JPEG, PNG, WebP) based on the image content and desired quality.
  • Test on various devices: Ensure your responsive images look and perform well on different screen sizes and browsers.

By effectively using srcset, sizes, and the picture element, you can create responsive images that enhance the user experience and improve page load times.

Modern Image Formats | Responsive Images
Art direction with the picture element | Responsive Images

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?