CSS - object-fit



The object-fit property in CSS is used to specify how an image or video should be resized or cropped to fit within its container.

Possible Values

The property takes a single value and that is a keyword, which is listed below:

  • contain: Image/video is scaled to fit within the container while maintaining its aspect ratio. It may leave empty space within the container.

  • cover: Image/video is scaled to cover the entire container while maintaining its aspect ratio. This might result in some parts of the image/video being clipped.

  • fill: Image/video fills the container completely, possibly distorting its aspect ratio.

  • none: Image/video is displayed at its original size, regardless of the container size. It may overflow the container.

  • scale-down: Image/video is scaled down to fit within the container if it was larger than its original size, otherwise, it's displayed at its original size.

Applies to

Replaced elements, such as images, videos, etc.

DOM Syntax

object.style.objectFit = "contain | cover | fill | scale-down | none";

CSS object-fit Example

The following example demonstrates how to use object-fit property with different values such as contain, cover, fill, scale-down, none −

<html>
<head>
<style>
   h2 {
      font-family: Verdana, Geneva, Tahoma, sans-serif;
      font-size: 1em;
      margin: 1em 0 0.3em;
   }

   img {
      width: 150px;
      height: 100px;
      border: 1px solid #000;
      margin: 10px 0;
   }

   .fill {
      object-fit: fill;
   }

   .contain {
      object-fit: contain;
   }

   .cover {
      object-fit: cover;
   }

   .none {
      object-fit: none;
   }

   .scale-down {
      object-fit: scale-down;
   }
</style>
</head>
<body>
   <div>
      <h2>object-fit: fill</h2>
      <img class="fill" src="images/orange-flower.jpg" alt="object-fit: fill" />

      <h2>object-fit: contain</h2>
      <img class="contain" src="images/orange-flower.jpg" alt="object-fit: contain" />

      <h2>object-fit: cover</h2>
      <img class="cover" src="images/orange-flower.jpg" alt="object-fit: cover" />

      <h2>object-fit: none</h2>
      <img class="none" src="images/orange-flower.jpg" alt="object-fit: none" />

      <h2>object-fit: scale-down</h2>
      <img class="scale-down" src="images/orange-flower.jpg" alt="object-fit: scale-down" />
   </div>
</body>
</html>
Advertisements