The object-fit and the object-position css property together provide us with the power to manipulate an image or a video and create some magic.
The object-fit CSS property is used to specify how an or should be resized to fit its container and the object-position css property is used together with object-fit to specify how an or should be positioned with x/y coordinates inside its “own content box”. Together they provide us with the power to manipulate an image or a video and create some magic.
This property defines how an image or a video fits inside its content box.
The object-fit
property can have the following values:
fill(default)
– The replaced content is sized to fill the element’s content box. If necessary, the object will be stretched or squished to fitcontain
– The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content boxcover
– The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. The object will be clipped to fitnone
– The replaced content is not resizedscale-down
– The content is sized as if none or contain were specified (would result in a smaller concrete object size)The object-position
property is used together with object-fit to specify how an <img>
or <video>
should be positioned with x/y coordinates inside its “own content box”.
The object-position property is used together with object-fit property to move the image around the content box. The default value it takes is object-position: 50% 50%
. This is the reason when we apply object-fit: cover
the image is positioned in center by default. The x/y coordinates can take a ‘px’ value or a ‘percentage’ value.
img {
width: 100%;
height: 100%;
object-fit: none;
object-position: 5px 10%;
}
The above code resizes an image to fit its content box, and position the image 5px from the left and 10% from the top inside the content box.
Apart from providing x/y coordinates values, object-position supports values like ‘bottom’, ‘center’, ‘top’, ‘left’ and ‘right’ which are self-explanatory.
Browser support
object-fit
and object-position
is supported by all latest version of browser except IE.