CSS object-fit
Subject: css
CSS object-fit
The object-fit
property in CSS is used to specify how an image or video should be resized to fit its container. It allows you to control the display behavior of replaced elements (like <img>
or <video>
) when the aspect ratio of the content differs from the container.
Why Use object-fit?
- Prevents image distortion or stretching
- Maintains proper aspect ratio
- Helps build responsive layouts with consistent image display
- Useful for thumbnails, banners, cards, and profile pictures
Syntax
Common Values
fill
: Default. Stretches the content to fill the container, which may distort the image.contain
: Scales the content to maintain aspect ratio and fit within the container.cover
: Scales the content to maintain aspect ratio and fill the container. May crop.none
: No resizing. Content overflows if it's too big.scale-down
: Uses the smaller result of eithernone
orcontain
.
Example: Comparing object-fit Values
Use Cases
- Covering a thumbnail container: Maintain aspect ratio while filling the box
- Image galleries or cards: Keep all images sized consistently without distortion
- Background-style image cropping: Create consistent visuals with cropping
Browser Support
Fully supported in all modern browsers including Chrome, Firefox, Edge, and Safari. Not supported in Internet Explorer.
Best Practices
- Use with fixed container size (width and height) to see consistent results
- Use
object-position
to control alignment (e.g.,top
,center
,bottom
) - Use
cover
for visually consistent thumbnails - Use
contain
for full image display without cropping
Key Takeaways
object-fit
controls how media fills its container boxcover
andcontain
are most commonly used for responsive image handling- Helps maintain aspect ratio and avoid image distortion
- Ideal for modern UI elements like cards, profile images, and galleries
Advertisement Slot 1
Advertisement Slot 2