Object Fit in CSS
? object-fit in CSS
The object-fit property controls how replaced elements like images or videos fit inside their container, especially when their intrinsic size doesn’t match the container’s size.
Syntax
img { object-fit: fill | contain | cover | none | scale-down;}Values
| Value | Description |
|---|---|
fill | Stretches the content to fill the container, may distort the aspect ratio |
contain | Scales the content to fit inside the container while preserving aspect ratio, may leave gaps |
cover | Scales the content to cover the entire container, cropping if necessary, preserves aspect ratio |
none | Keeps the original size of the content, may overflow container |
scale-down | Scales the content down to fit if it's larger than the container, otherwise behaves like none |
Example
img { width: 300px; height: 200px; object-fit: cover;}The image will cover the 300x200 container fully.
It maintains aspect ratio.
Parts of the image might be cropped.
Use Cases
Displaying responsive images or videos.
Creating image galleries with consistent item sizes.
Controlling how media fills its container without distortion.
Want me to help with examples combining object-fit with object-position for better control?