How to Display Different Images Based on Screen Sizes in HTML

How to Display Different Images Based on Screen Sizes in HTML

Ferenc Almasi β€’ 2020 September 15 β€’ Read time 1 min read
  • twitter
  • facebook
HTML

You can create responsive images right inside HTML, by using the srcset and sizes attributes on images:

Copied to clipboard! Playground
<!-- 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" />
screensizes.html

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.

How to Display Different Images Based on Screen Sizes in HTML
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
HTML
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.