D DevBrainBox

CSS Object Fit

CSS

What is object-fit?

The object-fit property defines how the content of a replaced element (like <img> or <video>) should fit within its box, especially when the aspect ratio doesn’t match.

  • It works like background-size for images/videos.

Common Syntax

img {
  width: 300px;
  height: 200px;
  object-fit: cover;
}
ValueDescription
fillStretches the image to fill the box. May distort it.
containResizes the image to fit entirely in the box. Keeps aspect ratio.
coverImage fills the box, may crop edges. Keeps aspect ratio.
noneImage keeps its original size, overflows if bigger than the box.
scale-downChooses the smaller of none or contain

Visual Example

cover

img {
  object-fit: cover;
}
Fills the box completely, cropping if necessary.

contain

img {
  object-fit: contain;
}
Fits inside the box without cropping, may leave empty space.

Example

<div class="image-box">
  <img src="photo.jpg">
</div>

.image-box {
  width: 300px;
  height: 200px;
  overflow: hidden;
}

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

On this page