WebMasterCampus
WEB DEVELOPER Resources

CSS Auto Resize an Image Inside a Div Container

Learn how using CSS Auto Resize an Image Inside a Div Container


Resize an image inside a div is easy. You need to follow the following steps to accomplish this.

  1. Apply 100% max-width and max-height to image (if you want to apply this to all images.Otherwise use a class for particular images) img{ max-width: 100%; max-height: 100%;}
  2. Apply width and height to the container of the image. .bannerImage{ width: 300px; height: 200px; }

Please note here we are using max-width not the width. max-width will give you a nice clear image according to aspect ratio of container width. If you will use width than the image will stretch with fixed with and height.

Example


<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width">
  <style>
    img{
      max-width: 100%;
      max-height: 100%;
    }
    .bannerImage{
      width: 300px;
      height: 200px;
    }

    .galleryImage{
      width: 300px;
      height: 150px;
    }

    .hoverImage{
      width: 300px;
      height: 100px;
         }
  </style>
</head>
<body>
  <div class="bannerImage">
    <img src="https://images.unsplash.com/photo-1518259102261-b40117eabbc9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" />
  </div>

  <div class="galleryImage">
    <img src="https://images.unsplash.com/photo-1518259102261-b40117eabbc9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" />
  </div>

  <div class="hoverImage">
<img src="https://images.unsplash.com/photo-1518259102261-b40117eabbc9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" />
  </div>
  <img src="https://images.unsplash.com/photo-1518259102261-b40117eabbc9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" />
</body>
</html>
Created with love and passion.