# CSS `object-fit`

The `object-fit` property specifies how the content of a replaced element, such as an `<img>` or `<video>`, should be resized to fit its container.

## 1. The Problem

Images have an intrinsic aspect ratio. If you set both `width` and `height` on an image to force it into a specific size (e.g., a square), the image will stretch and distort (squish) by default. `object-fit` fixes this.

## 2. Values

*   **`fill`** (Default): The image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit.
*   **`contain`**: The image keeps its aspect ratio, but is resized to fit within the given dimension. The image will be letterboxed if the aspect ratio doesn't match.
*   **`cover`**: The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit.
*   **`none`**: The image is not resized.
*   **`scale-down`**: The image is scaled down to the smallest version of `none` or `contain`.

## 3. Examples

```css
img {
  width: 200px;
  height: 200px;
  border: 1px solid #000;
}

.fill {
  object-fit: fill; /* Stretched */
}

.contain {
  object-fit: contain; /* Letterboxed */
}

.cover {
  object-fit: cover; /* Cropped */
}
```

## 4. `object-position`

By default, the image is centered in its content box. You can use the `object-position` property to change this alignment (similar to `background-position`).

```css
img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  object-position: top center; /* Focus on the top part of the image */
}
```

Values can be keywords (`top`, `bottom`, `left`, `right`, `center`) or percentages/lengths (`50% 50%`, `10px 20px`).

[[programming/css/css]]
[[programming/css/box-model]]
[[programming/css/positioning]]