
How to Display Different Images Based on Screen Sizes in HTML
You can create responsive images right inside HTML, by using the srcset
and sizes
attributes on images:
<!-- Use srcset with sizes to display different images based on screen size -->
<img srcset="small-nickcage.jpg 320w,
medium-nickcage.jpg 768w,
large-nickcage.jpg 1024w"
sizes="(max-width: 320px) 280px,
(max-width: 768px) 720px,
1024px"
src="large-nickcage.jpg"
alt="No need for introduction, you already know him" />
Copied to clipboard!
srcset
defines a comma-separated list of images with their intrinsic size. On the other hand, sizes holds a list of media queries with preferred image sizes. Meaning that if the browser matches the media query, the image will be displayed on the size specified next to the query.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Resources:
Tired of looking for tutorials?
You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.
Check out our interactive course to master JavaScript in less time.
Learn More