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.


<!DOCTYPE html>
<html lang="en">
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      background-color: #FFF123;
      background-color: orangered;
      border: 2px solid black;
      height: 400px;
      width: 20em;
      width: 100%;
      height: 100%;
      object-fit: cover;
      <div class="container">
         <img src="" 

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 »


Comments and Discussions!


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

© some rights reserved.