Signup/Sign In

How to create an responsive image with CSS?

In today's world, devices are of different sizes. From small mobiles to large computers. So when we add the image to a web page, it should adjust itself according to the size of the device.

This type of image is called a responsive image. We can add responsive images to an HTML program using CSS properties.

CSS properties for responsive image

The first way to create a responsive image is by adding the height of the image and width to 100%. We can also add the @media query to adjust the width of the image on different size devices.

Example: Create a responsive image with height and width property

In this program, we will add a <image> with class="responsive" . Further, we will add height and width="100%" to the responsive class to make the image responsive.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      img {
        width: 100%;
        height: 200px;
        border: 1px solid blue;
      }
    </style>
  </head>
  <body>
    <h1>Responsive Images Example</h1>
    <h2>Resize the window to see responsive image scale up and down</h2>
    <img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1626954731-101156.png">
  </body>
</html>

Output

For large screen

responsive image

For small screen

responsive image large

Example: Add a responsive image using media query

We can use @media query to adjust the size of the image at different widths of the screen. use the @media with max-width or min-width property.

Conclusion

We can create responsive images by adding CSS property to the image. Either we can set width:100 or add the @media query rule to resize the image accordingly. We have illustrated it with examples.



About the author: