srcset and sizes attributes for responsive images

Background

Responsive images are essential for web performance and user experience

Attributes

The image TAG includes a couple of attributes, including the global attributes. We need to be aware of and how to use them.


<img 
  loading="lazy"  
  alt=""
  height="100"
  width="100"
  src=""
  srcset=""
  sizes="" />
       

Lazy Loading

Don't forget that there is no need anymore for JS lazy loading.


<img 
  loading="" />
       

<img 
  loading="lazy" />
    

Accessibility

Accessibility is important. The alt attribute is important for Screenreaders, but also SEO.


<img alt="" />

Aspect Ratio

When working with images, it is important to consider the aspect ratio and how it will impact the final result. It is often expressed as two numbers separated by a colon, such as 4:3 or 16:9. CSS can additionally support you. This reduces repainting when images are loaded. Always add width and height.


<img alt=""
  src="small.jpg"
  width="16"
  height="9" />
<style>
  img {
    aspect-ratio: auto 16 / 9;
    object-fit: cover;
  }
</style>

The Source

The default behavior of the img element is to request the image at its natural size, regardless of the viewport size, we use the src for this.


<img alt=""
  src="small.jpg" />

The SRCSET

Use the srcset attribute to provide different image sources based on viewport size. It defines a list of image sources and their pixel density or widths and allows the browser to choose the best source based on the viewport size and device pixel ratio.


<img alt=""
  src="1x.jpg"
  srcset="1x.jpg 1x, 2x.jpg 2x" />
<img alt=""
  src="small.jpg"
  srcset="small.jpg 320w, medium.jpg 640w" />

The SIZES

Use the sizes attribute to defines a list of media queries and image sizes expected, this allows the browser to calculate the image size based on the viewport size and the specified conditions.


<img alt=""
  src="small.jpg"
  srcset="small.jpg 320w, medium.jpg 640w" />
  sizes="100vw" />
<img alt=""
  src="small.jpg"
  srcset="small.jpg 320w, medium.jpg 640w" />
  sizes="(min-width: 36em) 50vw, 100vw" />

SIZES in practice

The next example shows you a simple image loaded responsive into a 50vw container.

Enhanced SIZES in practice

The next example shows you a simple image loaded responsive into a CSS grid with different column layout for viewport.

And now. Look at this

You should be ready now.