ADVERTISEMENT
ADVERTISEMENT

How do I auto-resize an image to fit a 'div' container?

Learn how to auto-resize an image to fit a 'div' container using CSS?
Submitted by Shahnail Khan, on April 11, 2022

We embed an image into the document using <img> tag in HTML. By default, the image doesn't fit in a div container as it is either smaller or larger than the div container. In this article, we'll get to know how we can auto-resize an image to fit a div container.

We can auto-resize an image by using the object-fit property in CSS.

The object-fit property is used to fit the object (image or video) in the container whilst maintaining its aspect ratio. The object takes up the entire space of the container.

Set the value of object-fit to cover to "auto-resize" the image.

Example:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>object-fit</title>
   </head>
   
   <style>
      body{
      background-color: #FFF123;
      }
      .container{
      background-color: orangered;
      border: 2px solid black;
      height: 400px;
      width: 20em;
      }
      img{
      width: 100%;
      height: 100%;
      object-fit: cover;
      } 
   </style>
   
   <body>
      <div class="container">
         <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR2Us0ygule9jbbygOVLYuCDjLr2cJE95uccg&usqp=CAU" 
            alt="IncluHelp">
      </div>
   </body>
</html>

Output | Before using object-fit Property

Example | auto-resize an image (1)

As you can see, the image fits the div container without maintaining its aspect ratio. So, to maintain the aspect ratio, there is a use of the object-fit property.

Output | After using object-fit Property

Example | auto-resize an image (2)

As you can see, the image fills up the space and preserves the aspect ratio. This property value crops the left and right sides of the image. The image is auto-resized to fit the div container.

CSS Tutorial & Examples »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.