DEV Community

Cover image for Responsive Image Made Simple with srcset
Okanu Gracious
Okanu Gracious

Posted on

Responsive Image Made Simple with srcset

The srcset attribute is used in HTML to specify a list of images and their sizes. It allows the browser to choose the most appropriate image based on the device's screen size and resolution. This can be useful for optimizing the loading time of a webpage, as well as improving the user experience by displaying the best possible image quality.
Here's an example of how you might use the srcset attribute in an img element:

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="A description of the image">

In this example, the src attribute specifies the default image to display (small.jpg). The srcset attribute specifies two additional images (medium.jpg and large.jpg), along with their sizes in pixels (1000w and 2000w, respectively). The browser will use the src attribute as a fallback if it is unable to use the srcset attribute for some reason.

The srcset attribute can be used in conjunction with the sizes attribute to specify the size of the image in relation to the viewport:

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" sizes="(max-width: 600px) 50vw, 25vw" alt="A description of the image">```



In this example, the sizes attribute specifies that the image should be displayed at 50% of the viewport's width when the viewport is 600px or smaller, and 25% of the viewport's width when the viewport is larger than 600px.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)