DEV Community

Cover image for Responsive Images for web
Aneeqa Khan
Aneeqa Khan

Posted on

Responsive Images for web

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

Top comments (2)

Collapse
 
picwellwisher12pk profile image
Amir Hameed

Good information Aneeka. jazakAllah
Question: how attribute width and width in style is different? Why do you have to use it twice?

Collapse
 
aneeqakhan profile image
Aneeqa Khan

Thanks for mentioning Amir! I forgot to remove width property from the class.
Updated the example above now.