Example 2: Using object-fit: cover with an img Element

The object-fit: cover property can be used with an img element to achieve a similar effect. This property ensures that the image fills its container without distortion.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Image Fill Box without Distortion</title>
    <style>
        .image-box {
            width: 300px;
            height: 200px;
            overflow: hidden;
            position: relative;
        }
  
        .image-box img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
  
<body>
    <div class="image-box">
        <img src=
"https://media.w3wiki.org/wp-content/cdn-uploads/20190710102234/download3.png" 
            alt="Image">
    </div>
</body>
  
</html>


Output: In this example, the .image-box class sets the dimensions of the box and hides any overflow. The img element is styled to fill the box with width: 100% and height: 100%. The object-fit: cover property ensures that the image covers the box without distortion. The image is centered within the box using absolute positioning and the transform: translate(-50%, -50%) property.



How to Fill a Box with an Image Without Distorting in CSS ?

Filling a box with an image without distorting it can be a common requirement in web design. The goal is to ensure that the image covers the entire box while maintaining its aspect ratio. In this article, we will explore two methods to achieve this using CSS.

Similar Reads

Example 1: Using background-size: cover Property

The background-size: cover property is a simple and effective way to fill a box with an image without distorting it. It ensures that the image covers the entire box while preserving its aspect ratio, even if the box’s dimensions do not match the image’s aspect ratio....

Example 2: Using object-fit: cover with an img Element

...