CSS propertyEffects

object-fit

Decides how an image or video fills a box with different proportions.

Initial value
fill
Inherited
No
Animatable
no
Applies to
replaced elements, e.g. img, video, iframe
JavaScript
element.style.objectFit = "cover"
On this page

Example

#
CSS
.avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
}
Preview

Definition and usage

#

The object-fit property applies to replaced elements such as <img> and <video>. When you give them dimensions with different proportions from the file itself, by default the image is stretched and distorted (fill).

cover fills the whole box, cropping the excess, while contain fits the whole image, leaving empty strips. They are the equivalents of background-size: cover and contain, but for real images in HTML.

You choose the cropped part with the object-position property. By default the image is centred.

Syntax

#
Syntax
object-fit: fill | contain | cover | none | scale-down;

Values

#
  • fill

    The image is stretched to the box, the proportions are distorted.
  • cover

    The box is filled, the image edges are cropped.
  • contain

    The whole image is visible, with empty strips above and below it.
  • none

    The image at its natural size, clipped to the box.
  • scale-down

    The smaller of the none and contain options.

Values in practice

#

fill

The image is stretched to the box, the proportions are distorted.
.demo { object-fit: fill; }

cover

The box is filled, the image edges are cropped.
.demo { object-fit: cover; }

contain

The whole image is visible, with empty strips above and below it.
.demo { object-fit: contain; }

none

The image at its natural size, clipped to the box.
.demo { object-fit: none; }

scale-down

The smaller of the none and contain options.
.demo { object-fit: scale-down; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Thumbnails in a grid look uniform thanks to a fixed box (e.g. aspect-ratio: 1) and object-fit: cover.
  • For logos contain is better, so no part of the mark gets cut off.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.