Understanding object-fit CSS property

555 views Asked by At

In this article we can read:

The object-fit CSS property sets how the content of a replaced element, such as an <img> or <video>, should be resized to fit its container.

What does container mean in this case?

Parent element? Containing block?

1

There are 1 answers

0
Temani Afif On BEST ANSWER

From the specification:

The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

So it's neither the parent element nor the containing block but the element itself. It's a relation between the element and it's content. object-fit change the behavior of the content based on the dimension of the element.

Example with different elements sharing the same containing block:

img {
  object-fit: cover;
  border: 2px solid;
  width: 200px;
  height: 200px
}
<img src="https://picsum.photos/id/10/500/400">
<img src="https://picsum.photos/id/10/800/400">
<img src="https://picsum.photos/id/10/500/1000">
<img src="https://picsum.photos/id/10/600/300">

In all the above cases, the object-fit will try to cover the 200x200 area desfined by the width/height applied to the element. The containing block/parent element is irrelevant here and play no role.

In the same specification you can also read the keyword "the content box" or "element's content box" which is the container your are looking for.

Related:

How does object-fit work with canvas element?

CSS object-fit: contain; is keeping original image width in layout