CSS object-fit
The CSS object-fit
property is used to control how an image or video should be resized to fit within its container. It defines how the content of a replaced element (such as an <img>
or <video>
tag) should be scaled and aligned when its aspect ratio differs from that of its container.
The syntax for the object-fit
property is as follows:
selector {
object-fit: value;
}
selector
: Represents the HTML element or class to which theobject-fit
property will be applied. It is typically used with<img>
and<video>
elements.value
: Specifies how the content should be fitted. It can take one of the following values:fill
: The content is stretched to fill the entire container, potentially causing it to lose its aspect ratio and be distorted.contain
: The content is scaled to fit within the container while maintaining its aspect ratio. It will be fully visible, and there may be empty spaces within the container if the aspect ratios do not match.cover
: The content is scaled to cover the entire container while maintaining its aspect ratio. It may be clipped, and parts of the content may be hidden if the aspect ratios do not match.none
: The content retains its original size, and any overflowing content will be visible outside the container.scale-down
: The content is scaled down to fit within the container, but it will not be scaled up if it is smaller than the container. It is the equivalent ofcontain
ornone
, depending on which one results in a smaller concrete object size.
Example:
img {
width: 200px;
height: 150px;
object-fit: cover;
}
In this example, the <img>
element will have a fixed width and height of 200px
and 150px
, respectively. The object-fit
property is set to cover
, so the image will be scaled to cover the entire container while maintaining its aspect ratio. Parts of the image may be cropped if the aspect ratio of the image and the container differ.
The object-fit
property is a useful tool for creating responsive and visually appealing layouts when dealing with images and videos. By choosing the appropriate value, you can ensure that the content fits neatly within its container without being distorted or stretched.
It’s important to consider browser compatibility when using the object-fit
property, as it may not be fully supported in older browsers. Always test your styles on different browsers and devices to ensure consistent behavior.