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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay