How to useobject-fit Property in CSS

The object-fit property specifies how the content of a replaced element, such as an <img> or <video>, should be resized to fit its container. Using object-fit: contain; ensures that the image’s aspect ratio is preserved as it scales to fit the container.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <title>Object Fit Example</title>
  
    <style>
        .container {
            width: 100%;
            height: 300px;
            overflow: hidden;
        }
  
        .container img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    </style>
</head>
  
<body>
    <div class="container">
        <img src=
"https://media.w3wiki.org/wp-content/cdn-uploads/20190710102234/download3.png" 
        alt="Object Fit Image">
    </div>
</body>
  
</html>


Output

How to Control the Size of an Image without Stretching in CSS ?

Controlling the size of an image while maintaining its aspect ratio is a common challenge in web design. Directly setting an image’s width and height can lead to stretching or squashing, distorting the original aspect ratio. Fortunately, CSS offers several techniques to resize images without distortion. This article explores various approaches to achieve this, ensuring your images remain responsive and visually appealing.

Table of Content

  • Approach 1: Using max-width and max-height
  • Approach 2: Using object-fit Property
  • Approach 3: Using background-image

Similar Reads

Approach 1: Using max-width and max-height

Setting max-width and max-height properties allow an image to scale down if it’s too large but remain unchanged if it’s smaller than the maximum dimensions specified. This approach maintains the image’s aspect ratio automatically....

Approach 2: Using object-fit Property

...

Approach 3: Using background-image

The object-fit property specifies how the content of a replaced element, such as an or