What Is the CSS Object-Fit Property for Images?
The CSS object-fit property defines how an embedded
element, such as an <img> or
<video>, adjusts its dimensions to fit into its
designated container box. By default, applying explicit
width and height values to an image can
distort its native aspect ratio. Using object-fit allows
developers to control whether the image stretches, clips, or letterboxes
within its parent container while preserving its visual proportions,
making it a critical tool for responsive web design.
How CSS Object-Fit Works
When an image is placed on a webpage, it carries intrinsic dimensions
(its original width and height). If CSS forces the element into a box
with a different aspect ratio, standard rendering squishes or stretches
the pixel data. The object-fit property acts similarly to
background-size, but it applies directly to replaced inline
elements rather than background assets.
Primary Values of Object-Fit
The property accepts five distinct keyword values, each handling container constraints differently:
fill: The default behavior. The image is resized to completely fill the element's box. If the aspect ratios do not match, the image distorts to fit the exact dimensions.contain: Scales the image proportionally so that the entire image remains visible within the box. It stops scaling once the largest dimension hits a container boundary, often resulting in empty space (letterboxing or pillarboxing).cover: Scales the image proportionally to ensure the entire box is covered. If the aspect ratios do not match, parts of the image are clipped outside the container boundaries.none: Completely ignores the parent element’s sizing dimensions and displays the image at its original intrinsic size.scale-down: Compares the outcome ofnoneandcontain, dynamically applying whichever results in a smaller rendered object size.
Practical Example
To implement object-fit, both the width and height of
the image element must be explicitly set or constrained by layout
systems like Flexbox or CSS Grid:
.card-thumbnail {
width: 100%;
height: 250px;
object-fit: cover;
object-position: center;
}Complementing with Object-Position
While object-fit dictates how the image scales and
crops, the companion property object-position determines
which part of the cropped image remains visible. By default, elements
center within their bounding box (50% 50%), but developers
can shift the focal point to values like top left,
center top, or specific percentage coordinates to prevent
crucial visual details from being cropped out.