How to auto-resize an image to fit a div container using CSS?
To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container. It tells the content how to fit in a specific div container in various way such as preserve that aspect ratio or stretch up and take up as much space as possible.
- Example 1: This example describes the auto-resize image fit to div container. This example does not contain object-fit property.
In the above example as the object-fit property is not used, the image is being squeezed to fit the container, and its original aspect ratio is destroyed.
- Example 2: This example is used to display the part of image when use resize the div container.
Note: Using object-fit: cover; will cut off the sides of the image, preserving the aspect ratio, and also filling in space.
- Example 3: This example displays an image without using object-fit property. In this example, the size of the image is set manually and the image will not be able to maintain its aspect ratio and adjust or resize according to div container on resizing the browser window.
- Example 4: This example displays the part of image or image using object-fit property. In this example, the size of the image is set manually and the object-fit property is also used. In this case, on resizing the browser the image will maintain its aspect ratio and will not be resized according to div container.
- Note: The property object-fit: cover; will cut the sides of the image, preserving the aspect ratio, and also filling in space.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!