object-fit and object-position

Back to the index.

Two properties for objects, which mostly means images, but might also mean videos and anything else that’s embedded in a page.

object-fit

The object-fit property determines how the object fits into its box. In this example the object is an image of 189x24 pixels which is forced inside a box of 75x40 pixels. Not only is the box way too small, it also has a different aspect-ratio than the image.

<img src="/pix/logo_quirksmode.gif">

img {
	margin: 10px 0;
	width: 75px;
	height: 40px;
	border: 5px double;
	overflow: hidden;
}

fill (default)

The default is fill, which tells the image to fill the entire box and ignore its own aspect-ratio. This is the effect we have known since time immemorial.

contain

The contain value tells the image to shrink or enlarge itself until it fits in the box while maintaining its aspect-ratio.

cover

The cover value tells the image to shrink or enlarge itself until it fills up the box completely while maintaining its aspect-ratio. This usually results in only part of the image being shown.

none

The none value tells the image to ignore the box and retain its own size. This may result in the image not filling up the box or sticking out of it.

scale-down

The scale-down value tells the image to compare the results of none and contain and choose the one that results in the smallest image. In this test page that would be contain.

object-position

If an image does not coincide exactly with its box, it should be possible to position it somewhere; for instance in the lower right corner. All images below have object-fit: none and are positioned at various spots in the box.

bottom right

75% 25%