Using object-fit to position images in CSS

Choosing two of three priorities when displaying an image

December 18, 2022

Images are replaced elements

Images in HTML are rather unusual. They're inline elements, but they can be given a height, whereas most inline element's can't be given a height.

They're also replaced elements, where the <img> tag is replaced with a foreign object (the image itself).

In CSS, a replaced element is an element whose representation is outside the scope of CSS; they're external objects whose representation is independent of the CSS formatting model.

Put in simpler terms, they're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.1

Typical replaced elements: <iframe>, <video>, embed, img.

Choosing fit priorities with object-fit

There are three priorities deciding how to display an image: and we can only choose two.

  1. Preserving the aspect ratio
  2. Being able to see all the image data
  3. Filling the available space

object-fit allows us to choose which two to prioritize.

  • fill is the default value, it will distort the image to have it fit precisely within its container.
  • contain will preserve the aspect ratio to make the image fit completely within its container, usually leaving empty space on the top or sides.
  • cover will completely fill the container while preserving the aspect ratio, resulting in part of the image being cut off. This is the one I usually use.
  • none allows the image to remain at its natural size, but it crops whatever doesn't fit into the <img> DOM node. This often results in only the top-left corner of a huge image showing up.

The object-fit CSS property sets how the content of a replaced element, such as an <img> or <video>, should be resized to fit its container.2

Adjusting the anchor point with object-position

object-position allows us to choose where the anchor point of the image is when we use object-fit: cover to cover the container, but cut off some of the image. ![[Pasted image 20221218234535.png]] It takes, a horizontal and vertical offset, with the default value being 50% 50%.

We can even use keywords to choose where to anchor the image, for example object-position: left top;.

Some of this content is based on Josh Comeau's excellent CSS resources.