HTML srcset Attribute Explained
sizes attributes on
source) elements allow authors to define various image resources and “hints” that assist a user agent to determine the most appropriate image source to display (e.g. high-resolution displays, small monitors, etc).
Typically, when you embed an image into a page, you only define one “source”, in the form of the src attribute, like so:< img src=”/images/whatever.jpg” alt=”whatever”>
srcset attribute allows you to add other versions of the image, set the screen width at which those images are meant to appear, and let the browser make the decisions. This means that the user’s device only downloads the right image for their screen size.
You would set it up like so:< img src=”/images/whatever-small.jpg” srcset=”whatever-medium.jpg 1000w, whatever-large.jpg 2000w” alt=”whatever”>
- You’re letting the browser do the math. Picking the right image for the right screen size can be tricky, and if you’re using a lot of images, you probably don’t want to bother.
- You’re saving bandwidth. This means lower hosting costs for you, and lower data costs for mobile users.
- Partial browser support. In fact, this is the second-best-supported option on the list.
In the end, using the srcset attribute on a single <img> tag is probably the option that people will use most in the future. It just makes sense, when most of us will simply be using several differently-size versions of the same image, in order to save bandwidth.
Browser Support: https://caniuse.com/#search=srcset