What Is the CSS Object-Fit Property for Images?

The CSS object-fit property defines how an embedded element, such as an <img> or <video>, adjusts its dimensions to fit into its designated container box. By default, applying explicit width and height values to an image can distort its native aspect ratio. Using object-fit allows developers to control whether the image stretches, clips, or letterboxes within its parent container while preserving its visual proportions, making it a critical tool for responsive web design.

How CSS Object-Fit Works

When an image is placed on a webpage, it carries intrinsic dimensions (its original width and height). If CSS forces the element into a box with a different aspect ratio, standard rendering squishes or stretches the pixel data. The object-fit property acts similarly to background-size, but it applies directly to replaced inline elements rather than background assets.

Primary Values of Object-Fit

The property accepts five distinct keyword values, each handling container constraints differently:

Practical Example

To implement object-fit, both the width and height of the image element must be explicitly set or constrained by layout systems like Flexbox or CSS Grid:

.card-thumbnail {
  width: 100%;
  height: 250px;
  object-fit: cover;
  object-position: center;
}

Complementing with Object-Position

While object-fit dictates how the image scales and crops, the companion property object-position determines which part of the cropped image remains visible. By default, elements center within their bounding box (50% 50%), but developers can shift the focal point to values like top left, center top, or specific percentage coordinates to prevent crucial visual details from being cropped out.