1. css
  2. /properties
  3. /object-fit

object-fit

Definition

The object-fit property specifies how the contents of an element with a defined width and height should be resized and positioned to fit within its container. It is typically used to control the scaling and positioning of images or videos.

Examples

This example demonstrates how to use object-fit: cover to scale an image to cover the entire container while maintaining its aspect ratio:

<div class="container">
  <img src="image.jpg" alt="Image" class="image">
</div>
.container {
  width: 400px;
  height: 200px;
  overflow: hidden;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

This example demonstrates how to use object-fit: contain to scale an image to fit entirely inside the container while maintaining its aspect ratio:

<div class="container">
  <img src="image.jpg" alt="Image" class="image">
</div>
.container {
  width: 400px;
  height: 200px;
  overflow: hidden;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

This example demonstrates how to use object-fit: none to prevent any scaling or positioning of the contents of the container, causing it to overflow:

<div class="container">
  <img src="image.jpg" alt="Image" class="image">
</div>
.container {
  width: 400px;
  height: 200px;
  overflow: hidden;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: none;
}

Values

ValueDescription
fillResize the contents to fill the container, ignoring the aspect ratio
containScale the contents to fit entirely inside the container while maintaining the aspect ratio
coverScale the contents to cover the entire container while maintaining the aspect ratio
noneDo not resize or position the contents, causing them to overflow the container
scale-downScale the contents down to fit entirely inside the container if they are larger than the container, or use contain if they are smaller

Best Practices

  • Always set a defined width and height on the container element, and use overflow: hidden to prevent the contents from overflowing.
  • Use object-fit: cover for images that should fill the entire container while maintaining their aspect ratio, and use object-fit: contain for images that should fit entirely inside the container.
  • Avoid using object-fit: none unless you have a specific reason to do so, as it can cause the contents to overflow the container and potentially break the layout.
  • Use object-position in conjunction with object-fit to control the position of the contents within the container.
  • Test your layout on different devices and screen sizes to ensure that the scaling and positioning of the contents work well across a range of devices.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera
YesYesYesYesYesYes