How to auto-resize an image to fit a 'div' container using CSS?

CSS | Auto-resize an Image: In this tutorial, we will learn how to auto-resize an image to fit a 'div' container using CSS with the help of examples? By Shahnail Khan Last updated : July 12, 2023

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.

Auto-resize an image to fit a 'div' container using CSS

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 Examples »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.