csshtmlimageresponsive-design

HTML picture or srcset for responsive images


Making images responsive has always been a troublesome aspect of responsive web design for many. I have gone through a few of the articles regarding the same and came across "srcset" and "picture" as a solution for this.

SRCSET Example

  <img src="flower_500px.jpg"
     srcset="flower_750px.jpg 1.5x, flower_1000px.jpg 2x"
     width="500px" alt="flower">

PICTURE Example

  <picture>
      <source media="(min-width: 45em)" srcset="flower_1000px.jpg">
      <source media="(min-width: 32em)" srcset="flower_750px.jpg">
      <img src="flower_500px.jpg" alt="flower">
  </picture>

I'm trying to decide which of those two methods to choose to make images responsive. What are the characteristics that I should consider in this choice?


Solution

  • As of 2022, both picture and srcset are compatible with all modern browsers. However, if an older browser doesn't understand the <picture> element, it will gracefully fall back to the <img> element inside of it. If an older browser doesn't understand <img srcset...> it will fall back to using the src attribute of the image.

    The <picture> element (and <source> sub-elements) are the heavy guns you bring in when you want to do art direction on different sizes / aspect ratios of the image. The img srcset attribute is much more lightweight and is all you need if you want to design for different resolution displays.

    Because both are widely supported, I would not worry too much about which one you use. If you're only designing for pixel density, I would recommend srcset because it's more lightweight. (By lightweight, I mean it takes less code to write out.)