The object-fit property is used to control how an image or other replaceable content is resized and positioned within its container. It’s especially useful for ensuring images maintain their aspect ratio while fitting into different container sizes.
Syntax
object-fit: fill | cover | contain | scale-down | none;
Values
- fill: Resizes the image to fill the container, potentially distorting its aspect ratio.
- cover: Resizes the image to completely cover the container, maintaining its aspect ratio and possibly cropping portions of the image.
- contain: Resizes the image to fit within the container while maintaining its aspect ratio, possibly leaving empty space around it.
- scale-down: Similar to
contain, but if the image is larger than the container, it will be scaled down to fit without cropping. - none: The image is displayed in its original size and position within the container, potentially overflowing if it doesn’t fit.
Example
<div style="width: 200px; height: 100px;">
<img src="image.jpg" alt="Image" style="object-fit: cover;">
</div>
In this example, the image will be resized to cover the entire 200px by 100px container, maintaining its aspect ratio and possibly cropping portions of the image to fit.
Additional Considerations
- The
object-fitproperty only applies to replaceable content, such as images, videos, and SVG elements. - If you want to control the alignment of the image within the container, you can use the
object-positionproperty. - For more complex image manipulation, consider using JavaScript libraries or CSS filters.