Tip #32: Improve images by using the picture tag

  • — Frontend

  • 1 min. read

  • — 2/25/2023

In the previous tip I talked about optimizing your images using the loading attribute. Continuing with the theme, I want to talk about using a newer HTML tag called picture to build better-optimized images.

The picture tag looks something like this:

    <source srcset="..."></source>
	<img src="..."></img>


  • source defines a set of optimized images to load in certain contexts
  • img is our fallback, default image in case source isn't supported.

So in a picture element, source is our start player. It takes a special attribute called srcset which, you guessed it, defines a list of sources for our images (almost like an array).

The syntax for srcset is a little nuanced and I feel the MDN docs do it more justice than I can. Nonetheless, I can sum up the attribute. The idea is that we can define multiple versions of our image inside of a picture tag and use the srcset attribute to select a particular version depending on the screen-size.

So for example, let's say we have a background image for our hero section and we're using a picture tag for it. On mobile, we can have a particular image be the background image. On tablet we can have another. Then, finally, we have the desktop version.

All of these three images can be defined inside the srcset for source and all live together under one picture element.

The idea being that if we have optimized images for mobile, tablet, and desktop rather than one img trying to fit to all, then we've improved overall performance and UX.

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!