object-fit

Draft

Definition

The object-fit CSS property is used to control how an element, typically an <img> or <video> tag, should fit within its container. It specifies how the content of the element should be resized and positioned.

The object-fit property accepts various values:

  • fill: The content stretches to fill the entire container, potentially distorting its aspect ratio.
  • contain: The content maintains its aspect ratio and scales to fit within the container, leaving no empty space.
  • cover: The content maintains its aspect ratio and scales to cover the entire container, potentially cropping parts of it.
  • none: The content retains its original size and aspect ratio, overflowing the container if necessary.
  • scale-down: The content is scaled down to fit within the container if it is smaller than its natural size, otherwise, it behaves like none.

Here’s an example:

.image-container {
  width: 300px;
  height: 200px;
}

.image-container img {
  object-fit: cover;
}

In this example, the .image-container class represents a container with a fixed width and height. The <img> tag inside it has the object-fit: cover; rule, which scales the image to cover the entire container while maintaining its aspect ratio.

By using object-fit, you can control how the content within an element should fit within its container, ensuring proper sizing and aspect ratio while maintaining responsiveness.