object-fit
is a CSS property that sets how certain elements’ content is resized to fit their container.
The elements that are affected by the object-fit
property are called replaced elements.
In CSS, replaced elements are external objects whose representation is not in the CSS formatting model. Their representation is outside the scope of CSS.
The replaced elements in CSS are: code>img
, video
, iframe
, and embed
tags.
The syntax of the object-fit
is as follows:
property: value
It has its local values and global values.
The local values are:
object-fit: fill;
object-fit: contain;
object-fit: cover;
object-fit: none;
object-fit: scale-down;
fill
: The replaced element content is resized to fit in its container even if it requires being stretched or squished to fit. This is the default value.
contain
: The content is resized to fit its container but it keeps its aspect ratio no matter what.
cover
: The content fills its content by clipping just to fit, but it also keeps its aspect ratio.
none
: Here, the content is not resized.
scale-down
: The image is scaled down to the smallest version of none
or contain
.
The global values are:
object-fit: inherit;
object-fit: initial;
object-fit: revert;
object-fit: unset;
The work of the global values doesn’t change for all CSS properties.
Lines 6–9 are the presentation of one of the replaced elements.
Line 8 contains the img
tag, which has an image and a class: "fill"
.
Lines 1–6 (in the “CSS” tab) contain the property of the img
. Here, it is given a specified width and height and other values.
Lines 7–9 (in the “CSS” tab) set the object fit property to contain
. This makes the content fit in the container while keeping its aspect ratio.
Note: All other values are used the same way, depending on your desired output.