Responsive Images for web

Aneeqa Khan - Sep 2 '22 - - Dev Community

Recently I learned a new thing about responsive images and want to share it here.

As we all know, we can create responsive images through CSS and media queries but <picture> element allow us to show multiple images according to the browser viewport.

With CSS

First, let's see an example of responsive image using CSS

  <img
    src="./src/desktop-img.png"
    alt="desktop"
    class="responsive"
    width="100%"
  />
Enter fullscreen mode Exit fullscreen mode

and give it css properties

  .responsive {
     height: auto;
  }
Enter fullscreen mode Exit fullscreen mode


As you can see, image will get adjusted according to the width of the screen but this solution is not very convenient on smaller screens if the image is designed for large screens and also if the image contains text then that information can get lost.

With Picture element

<picture> element gives us flexibility to use different images for different screens.
The <picture> element contains two tags: one or more <source> tags and one <img> tag.
The <source> tag contains media and srcset properties. The browser will check the media query which matches the current viewport width and display that image specified in srcset property.
Lets see its example

<picture>
  <source media="(min-width:650px)" srcset="./src/desktop-img.png" />
  <source media="(min-width:465px)" srcset="./src/mobile-img.png" />
  <img src="./src/mobile-img.png" alt="desktop" style="width: 100%;" />
</picture>
Enter fullscreen mode Exit fullscreen mode

Here I'm showing a desktop-img for the viewports having a width greater and equal to 650px and mobile-img for the viewports having a width greater and equal to 465px.
And also I gave the default image in <img> tag. It'll show this image if none of the media query conditions are fulfilled.

You can read more about the <picture> tag here

Thank you for reading!
Feel free to connect on Twitter

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .