What is the new srcset and size attribute for in HTML?
The HTML img
size attribute is new to HTML and supported across most modern browsers. The
srcset attribute now allows us to load an image based on the screen dimension. The important part to note is that the selected image gets (downloaded) with the document.
Why is it needed?
The most important reason for using the srcset attribute is to reduce page loading speeds, Its a real waste of data to download a 1280px wide image on a device with a screen thats 600px wide.
Quick srcset and size sample
Important to note:
srcset attribute uses a descriptor, the descriptor tells the browser what defines the switch between the different images. For example, should we change the images based on the width of the screen or the DPI. The descriptor goes immediately after the image name.
x srcset=" sample_img_1xDPI.jpg 1x, sample_img_2xDPI.jpg 2x " /> w srcset=" sample_img_small.jpg 500w, sample_img_large.jpg 1000w " />
The sizes attr tells the browser what size the image should be displayed at. The sizes attr accepts multiple arguments seperated by a comma (,). The sizes attr also accepts media queries
srcset=" sample_img_small.jpg 500px, sample_img_large.jpg " sizes=" (min-width:1000px) 50vw, 100vw " />