CSS object-fit Property Tutorial

In this section, we will learn what the object-fit property is and how to use it in CSS.

Click here to run the example of object-fit property.

CSS object-fit Property Definition and Usage

When importing an image via <img> tag, by default, the width and height of that image will be equal to the size of the <img> tag. For this reason, there’s a high chance that the aspect ratio of the imported image becomes distorted.

So in order to preserve the aspect ratio of the imported image, CSS provided a property named `object-fit`.

Basically, using this property, we can declare how the target image should be displayed on the page.

CSS object-fit Property Syntax

object-fit: fill|contain|cover|scale-down|none|initial|inherit;

CSS object-fit Property Value

Here are the values we can use for this property:

  • fill: This is the default value and it makes the image to fit the size of its <img> tag.
  • cover: the imported image will be resized without distorting its aspect ratio in a way that it’ll fill the entire box of its <img> tag, which results in cutting off part of the image.
CSS property object-fit
  • contain: using this property means the target image should fit in the dimension of the target <img> element without distorting its aspect ratio. Using this value might result in part of the <img> box left empty.
CSS property object-fit
  • none: The imported image should not be resized.

scale-down: the imported image will be seized as if it was either “none” or “contain” whichever result in a smaller concrete object size.

Example: object-fit in CSS

See the Pen object-fit in CSS by Omid Dehghan (@enjoytutorials1) on CodePen.

Example: crop images with CSS

See the Pen crop images with CSS by Omid Dehghan (@enjoytutorials1) on CodePen.

Leave a Reply